是否可以将函数值存储在哈希表中?
我想将函数作为值存储在我的 Android 设备的哈希表中。这可能吗?
I want to store functions as values in a HashTable for my android device. Is that possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您可以使用所谓的 Reflection 来做到这一点。您可以创建某种类型的哈希表,如下所示:
这里有关于 方法 类。
也就是说,反思通常是一个坏主意。当你觉得需要使用反射时,你应该问自己,“我真的需要这样做吗?有什么方法可以在不使用反射的情况下完成我想要做的事情吗?”。如果经过几分钟的认真思考后,您的问题的答案仍然是“是的,我需要反思”,那么请继续使用它。
Yes, you can do that using what's called Reflection. You'd create some sort of HashTable, like this:
Here's more information on the Method class.
That said, reflection is generally a bad idea. When ever you feel the need to use Reflection, you should ask yourself, "Do I really need to do things this way? Is there some way I can accomplish what I'm trying to do with out reflection?". If after thinking very hard for several minutes the answer to your question is still "Yep, I need reflection", then go ahead and use it.
不,java不允许这样做。您可以做的是创建某种接口,允许您提供特定方法的自定义实现。
例如
,然后您可以创建此接口的自定义实现并将这些对象添加到哈希映射中。然后您可以检索对象并调用该方法。
No, java doesn't allow that. What you could do is create some sort of interface that allows you to provide custom implementations of a specific method.
For instance
And then you could create custom implementations of this interface and add those objects to a hashmap. Then you could retrieve the objects and call the method.
从Java7开始,您可以创建MethodHandles来表示函数(方法)。
当然,您可以将它们存储在任何地方,包括哈希表。
From Java7 on, you can create MethodHandles to represent functions (methods).
And of course, you can store 'em anywhere, including Hashtables.