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

前端 未结 21 2078
耶瑟儿~
耶瑟儿~ 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:33

    Method method = someVariable.class.getMethod(SomeClass);
    String status = (String) method.invoke(method);
    

    SomeClass is the class and someVariable is a variable.

提交回复
热议问题