If I have two variables:
Object obj;
String methodName = \"getName\";
Without knowing the class of obj
, how can I call the met
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);