Java动态函数调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3050967/
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
Java dynamic function calling
提问by dpaksp
I have a String array that contains names of method in the yyyyyy
class
我有一个包含yyyyyy
类中方法名称的字符串数组
In the xxxxxx
class I'm making a yyyyyy
instance (say obj
). Now I can call obj.function_name()
, except I want to read function_name
from the String array in a loop. Is this possible?
在xxxxxx
课堂上,我正在制作一个yyyyyy
实例(比如obj
)。现在我可以调用obj.function_name()
,除非我想function_name
在循环中从 String 数组中读取。这可能吗?
采纳答案by Bozho
You can, using reflection. It is done by calling Yyyy.class.getMethod("methodName").invoke(someArgs)
你可以,使用反射。它是通过调用完成的Yyyy.class.getMethod("methodName").invoke(someArgs)
You'd have to handle a bunch of exceptions, and your method must be public
. Note that java coding conventions prefer methodName
to method_name
.
您必须处理一堆异常,并且您的方法必须是public
. 需要注意的是Java编码惯例喜欢methodName
到method_name
。
Using reflection, however, should be a last resort. You should be using more object-oriented techniques.
然而,使用反射应该是最后的手段。您应该使用更多面向对象的技术。
If you constantly need similar features, perhaps you can look at some dynamic language running on the java platform, like Groovy
如果你经常需要类似的功能,也许你可以看看一些运行在java平台上的动态语言,比如Groovy
回答by Michael Mrozek
It's possible using reflection, although you should probably question your design somewhat if you need that sort of behavior. Class.getMethod
takes a String
for the method name and returns a Method
object, which you can then call .invoke
on to call the method
使用反射是可能的,但如果您需要这种行为,您可能应该对您的设计有所质疑。为方法名称Class.getMethod
取 aString
并返回一个Method
对象,然后您可以调用该对象.invoke
来调用该方法
These Javadoc pages should be helpful:
这些 Javadoc 页面应该会有所帮助:
Sample code (assuming the yyyyyy
methods take one int
argument, just to show argument passing):
示例代码(假设yyyyyy
方法采用一个int
参数,只是为了显示参数传递):
yyyyyy obj = new yyyyyy();
String[] methodNames = {"foo", "bar", "baz"};
for(String methodName : methodNames) {
Method method = Class.forName("yyyyyy").getMethod(methodName, new Class[] {int.class});
method.invoke(obj, 4); // 4 is the argument to pass to the method
}