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

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

    This is working fine for me :

    public class MethodInvokerClass {
        public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, ClassNotFoundException, InvocationTargetException, InstantiationException {
            Class c = Class.forName(MethodInvokerClass.class.getName());
            Object o = c.newInstance();
            Class[] paramTypes = new Class[1];
            paramTypes[0]=String.class;
            String methodName = "countWord";
             Method m = c.getDeclaredMethod(methodName, paramTypes);
             m.invoke(o, "testparam");
    }
    public void countWord(String input){
        System.out.println("My input "+input);
    }
    

    }

    Output:

    My input testparam

    I am able to invoke the method by passing its name to another method (like main).

提交回复
热议问题