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

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

    using import java.lang.reflect.*;

    public static Object launchProcess(String className, String methodName, Class[] argsTypes, Object[] methodArgs)
            throws Exception {
    
        Class processClass = Class.forName(className); // convert string classname to class
        Object process = processClass.newInstance(); // invoke empty constructor
    
        Method aMethod = process.getClass().getMethod(methodName,argsTypes);
        Object res = aMethod.invoke(process, methodArgs); // pass arg
        return(res);
    }
    

    and here is how you use it:

    String className = "com.example.helloworld";
    String methodName = "print";
    Class[] argsTypes = {String.class,  String.class};
    Object[] methArgs = { "hello", "world" };   
    launchProcess(className, methodName, argsTypes, methArgs);
    

提交回复
热议问题