how to call a java method using a variable name?

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