how to call a java method using a variable name?

后端 未结 4 1671
傲寒
傲寒 2020-11-28 09:52

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

Is there a way i can chose one of those with a variable?

 String MyVar=2;
 MethodMyVar();
4条回答
  •  隐瞒了意图╮
    2020-11-28 10:39

    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.

提交回复
热议问题