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

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

    Use method invocation from reflection:

    Class c = Class.forName("class name");
    Method method = c.getDeclaredMethod("method name", parameterTypes);
    method.invoke(objectToInvokeOn, params);
    

    Where:

    • "class name" is the name of the class
    • objectToInvokeOn is of type Object and is the object you want to invoke the method on
    • "method name" is the name of the method you want to call
    • parameterTypes is of type Class[] and declares the parameters the method takes
    • params is of type Object[] and declares the parameters to be passed to the method

提交回复
热议问题