java 在java中我可以将方法存储在变量中吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5933366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In java can i store a method in a variable?
提问by David
Possible Duplicate:
Java - Creating an array of methods
可能的重复:
Java - 创建方法数组
In java can i store a method in a variable? For example can i have an array of methods? If so how would i do this?
在java中我可以将方法存储在变量中吗?例如,我可以有一组方法吗?如果是这样,我将如何做到这一点?
采纳答案by T.J. Crowder
In Java 6 and below, you'd need to use reflection (see the java.lang.reflect
package). Java 7 is meant to have some new features in this regard (specifically method handles(JSR 292) and the new "invoke dynamic" stuff). Java 8 (some way off, then) looks set to have lambda expressions(and yes, that link is to an OpenJDK page, but they say Oracle's on board), which aren't quite the same thing, but are related.
在 Java 6 及更低版本中,您需要使用反射(请参阅java.lang.reflect
包)。Java 7 旨在在这方面拥有一些新功能(特别是方法句柄( JSR 292) 和新的“调用动态”内容)。Java 8(然后有一段距离)看起来设置为具有lambda 表达式(是的,该链接指向 OpenJDK 页面,但他们说 Oracle 已加入),它们并不完全相同,但相互关联。
回答by Rupeshit
I will recommend you to hold the output in a variable rather than calling the function again. Because the variable is going to be held in memory as long as it requires. After that automatic garbage collection will take care of that to free it up from the memory. But if you put method in variable that will eat up the memory for its activation record stack each time it gets called. So its good practice to store output in variable instead of method.
我建议您将输出保存在变量中,而不是再次调用该函数。因为只要需要,变量就会保存在内存中。在那之后,自动垃圾收集将负责将其从内存中释放出来。但是,如果您将方法放入变量中,则每次调用它时都会占用其活动记录堆栈的内存。因此,将输出存储在变量而不是方法中是一种很好的做法。
回答by Nico Huysamen
It is possible if you use reflectionand the Method
data type.
如果您使用反射和Method
数据类型,则是可能的。
回答by Premraj
You can use reflection to get Method
object and then you can call invoke(..) on it
您可以使用反射来获取Method
对象,然后您可以在其上调用 invoke(..)
回答by PeterMmm
Look what, for example, returns Class#getDeclaredMethods().
看看什么,例如,返回Class#getDeclaredMethods()。
回答by Amit Gupta
Yea reflection is one way. But you can use an interface.
是的,反射是一种方式。但是你可以使用一个接口。
interface I {
int add (int a, int b);
}
say you have a class
说你有一堂课
class B implements I {
int add(int a, int b){
return a + b;
}
}
now you can create a function like:
现在您可以创建一个函数,如:
doCalculate(I mehthodInterface) {
\some calculations
\u can also use any other functions defined in this interface
methodInterface.add(2, 3);
}
Here you can have array of interfaces that are implementing the methods.
在这里,您可以拥有实现方法的接口数组。