How do I invoke a Java method when given the method name as a string?

前端 未结 21 2087
耶瑟儿~
耶瑟儿~ 2020-11-21 04:50

If I have two variables:

Object obj;
String methodName = \"getName\";

Without knowing the class of obj, how can I call the met

21条回答
  •  迷失自我
    2020-11-21 05:26

    Object obj;
    
    Method method = obj.getClass().getMethod("methodName", null);
    
    method.invoke(obj, null);
    

提交回复
热议问题