how to call a java method using a variable name?

后端 未结 4 1673
傲寒
傲寒 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:43

    Use reflection:

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

提交回复
热议问题