开发者

how to call a java method using a variable name?

Say I have Method1(void), Method2(void)...

Is there a way i can chose one of those 开发者_开发技巧with a variable?

 String MyVar=2;
 MethodMyVar();


Use reflection:

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


Only through reflection. See the java.lang.reflect package.

You could try something like:

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

Your code may be different if the method has parameters and there's all sorts of exception handling missing.

But ask your self if this is really necessary? Can something be changed about your design to avoid this. Reflection code is difficult to understand and is slower than just calling obj.someMethod().

Good luck. Happy Coding.


You could use the Strategy design pattern and a mapping from the string you have to the corresponding concrete strategy object. This is the safe and efficient means.

So, have a HashMap<String,SomeInterfaceYouWantToInvokeSuchAsRunnableWithPseudoClosures> look-up.

E.g., something along the lines of:

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()

You could also use reflection or "invert" the problem and use polymorphism


I'm not sure how the accepted answer works for method.invoke() without first argument of static method being null(put dummy value still works though). According to The Java™ Tutorials:

The first argument is the object instance on which this particular method is to be invoked. (If the method is static, the first argument should be null.)

The following shows a complete examples (Main.java), for both static(by class) VS non-static(by instance), plus additional example for method with argument, import necessary class, catch exception, and also superclass method example.

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);
       }
    }
}

Output:

$ javac Main.java
$ java Main 
by class: 10000
by instance
calls super protected method by instance
calls super public method by instance
$ 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜