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

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

    You should use reflection - init a class object, then a method in this class, and then invoke this method on an object with optional parameters. Remember to wrap the following snippet in try-catch block

    Hope it helps!

    Class aClass = Class.forName(FULLY_QUALIFIED_CLASS_NAME);
    Method method = aClass.getMethod(methodName, YOUR_PARAM_1.class, YOUR_PARAM_2.class);
    method.invoke(OBJECT_TO_RUN_METHOD_ON, YOUR_PARAM_1, YOUR_PARAM_2);
    

提交回复
热议问题