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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:59:58  来源:igfitidea点击:

Java dynamic function calling

javareflection

提问by dpaksp

I have a String array that contains names of method in the yyyyyyclass

我有一个包含yyyyyy类中方法名称的字符串数组

In the xxxxxxclass I'm making a yyyyyyinstance (say obj). Now I can call obj.function_name(), except I want to read function_namefrom 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 methodNameto method_name.

您必须处理一堆异常,并且您的方法必须是public. 需要注意的是Java编码惯例喜欢methodNamemethod_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.getMethodtakes a Stringfor the method name and returns a Methodobject, which you can then call .invokeon to call the method

使用反射是可能的,但如果您需要这种行为,您可能应该对您的设计有所质疑。为方法名称Class.getMethod取 aString并返回一个Method对象,然后您可以调用该对象.invoke来调用该方法

These Javadoc pages should be helpful:

这些 Javadoc 页面应该会有所帮助:

Sample code (assuming the yyyyyymethods take one intargument, 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
}