如何使用变量名调用java方法?

假设我有Method1(void),Method2(void)……

有没有办法可以选择其中一个变量?

String MyVar=2; MethodMyVar(); 

使用reflection:

 Method method = WhateverYourClassIs.class.getDeclaredMethod("Method" + MyVar); method.invoke(); 

只有通过反思。 请参阅java.lang.reflect包。

你可以尝试类似的东西:

 Method m = obj.getClass().getMethod("methodName" + MyVar); m.invoke(obj); 

如果方法具有参数并且缺少各种exception处理,则您的代码可能会有所不同。

但问问你自己这是否真的有必要? 可以对您的设计进行更改以避免这种情况。 reflection代码很难理解,并且比调用obj.someMethod()慢。

祝你好运。 快乐的编码。

您可以使用策略设计模式以及从您拥有的字符串到相应的具体策略对象的映射。 这是安全有效的手段。

所以,有一个HashMap查找。

例如,有些东西:

 final static YourType reciever = this; HashMap m = new HashMap {{ add("a", new Runnable() { @Override public void run () { reciever.a(); } }); .... }}; // but check for range validity, etc. m.get("a").run() 

您也可以使用reflection或“反转”问题并使用多态

我不确定如果没有静态方法的第一个参数为null (尽管虚拟值仍然有效), method.invoke()接受的答案是如何工作的。 根据The Java™Tutorials :

第一个参数是要在其上调用此特定方法的对象实例。 (如果方法是静态的,则第一个参数应为null。)

下面显示了一个完整的示例( Main.java ),用于静态(按类)VS非静态(按实例) ,以及带参数的方法导入必要类, 捕获exception以及超类方法示例的附加示例。

 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 $