![](/img/trans.png)
[英]How to call a method whose name is the value of a string variable in java?
[英]how to call a java method using a variable name?
说我有Method1(void),Method2(void)...
有什么方法可以选择其中一个带有变量的变量吗?
String MyVar=2;
MethodMyVar();
使用反射:
Method method = WhateverYourClassIs.class.getDeclaredMethod("Method" + MyVar);
method.invoke();
只有通过反思。 请参阅java.lang.reflect
包。
您可以尝试类似:
Method m = obj.getClass().getMethod("methodName" + MyVar);
m.invoke(obj);
如果该方法具有参数,并且缺少各种异常处理,则您的代码可能会有所不同。
但是问问自己,这是否真的必要? 可以对您的设计进行一些更改以避免这种情况。 反射代码很难理解,并且比仅调用obj.someMethod()
慢。
祝好运。 编码愉快。
您可以使用策略设计模式以及从字符串到对应的具体策略对象的映射。 这是安全有效的手段。
因此,进行HashMap<String,SomeInterfaceYouWantToInvokeSuchAsRunnableWithPseudoClosures>
查找。
例如,类似于以下内容:
final static YourType reciever = this;
HashMap<String,Runnable> m = new HashMap<String,Runnable> {{
put("a", new Runnable() {
@Override public void run () {
reciever.a();
}
});
....
}};
// but check for range validity, etc.
m.get("a").run()
您还可以使用反射或“反转”问题并使用多态性
我不确定在没有静态方法的第一个参数为null
情况下, method.invoke()
的可接受答案如何工作method.invoke()
尽管虚拟值仍然有效)。 根据Java™教程 :
第一个参数是在其上调用此特定方法的对象实例。 (如果该方法是静态的,则第一个参数应为null。)
下面显示了完整的示例( Main.java ),包括静态(按类)VS非静态(按实例) ,以及带有参数的方法的其他示例, 导入必要的类, 捕获异常以及超类方法的示例。
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
class Love {
protected void Method4() {
System.out.println("calls super protected method by instance");
}
public void Method5() {
System.out.println("calls super public method by instance");
}
}
class Main extends Love {
static void Method2(int y) {
System.out.println("by class: " + y);
}
void Method3(String y) {
System.out.println(y);
}
public static void main(String[] args) {
String MyVar = "2";
String MyAnotherVar = "3";
String MySuperVar = "4";
String MySuperPublicMethodVar = "5";
Main m = new Main();
try {
Method method = Main.class.getDeclaredMethod("Method" + MyVar, int.class); //by class
Method anotherMethod = m.getClass().getDeclaredMethod("Method" + MyAnotherVar, String.class); //by instance
Method superMethod = m.getClass().getSuperclass().getDeclaredMethod("Method" + MySuperVar); //super method by instance, can be protected
Method superPublicMethod = m.getClass().getMethod("Method" + MySuperPublicMethodVar); //getMethod() require method defined with public, so even though sublcass calls super protected method will not works
try {
method.invoke(null, 10000);//by class
anotherMethod.invoke(m, "by instance"); //by instance
superMethod.invoke(m); //super method by instance
superPublicMethod.invoke(m); //super's public method by instance
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
输出:
$ javac Main.java
$ java Main
by class: 10000
by instance
calls super protected method by instance
calls super public method by instance
$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.