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

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

    Here are the READY TO USE METHODS:

    To invoke a method, without Arguments:

    public static void callMethodByName(Object object, String methodName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        object.getClass().getDeclaredMethod(methodName).invoke(object);
    }
    

    To invoke a method, with Arguments:

        public static void callMethodByName(Object object, String methodName, int i, String s) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
            object.getClass().getDeclaredMethod(methodName, int.class, String.class).invoke(object, i, s);
        }
    

    Use the above methods as below:

    package practice;
    
    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    
    public class MethodInvoke {
    
        public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {
            String methodName1 = "methodA";
            String methodName2 = "methodB";
            MethodInvoke object = new MethodInvoke();
            callMethodByName(object, methodName1);
            callMethodByName(object, methodName2, 1, "Test");
        }
    
        public static void callMethodByName(Object object, String methodName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
            object.getClass().getDeclaredMethod(methodName).invoke(object);
        }
    
        public static void callMethodByName(Object object, String methodName, int i, String s) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
            object.getClass().getDeclaredMethod(methodName, int.class, String.class).invoke(object, i, s);
        }
    
        void methodA() {
            System.out.println("Method A");
        }
    
        void methodB(int i, String s) {
            System.out.println("Method B: "+"\n\tParam1 - "+i+"\n\tParam 2 - "+s);
        }
    }
    

    Output:

    Method A  
    Method B:  
    	Param1 - 1  
    	Param 2 - Test

提交回复
热议问题