JAVA: Calling Unknown Object Class Method and Passing it's Parameters

instance, java, methods, object, parameters

Solution

I think you're just missing the fact that you can pass in arguments to `invoke`, as an `Object[]`:

Object result = methods[i].invoke(object, new Object[] { word });

Or using varargs, if you prefer:

Object result = methods[i].invoke(object, word);

(The above two calls are equivalent.)

See the documentation for `Method.invoke` for more details.

Problem

The objective is simple, I want to create a method which load a class dynamically, access its method and passing their parameters value and getting the return value at run-time. Class which will be called ``` class MyClass { public String sayHello() { return "Hello"; } public String sayGoodbye() { return "Goodbye"; } public String saySomething(String word){ return word; } } ``` Main Class ``` public class Main { public void loadClass() { try { Class myclass = Class.forName(getClassName()); //Use reflection to list methods and invoke them Method[] methods = myclass.getMethods(); Object object = myclass.newInstance(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().startsWith("saySome")) { String word = "hello world"; //**TODO CALL OBJECT METHOD AND PASS ITS PARAMETER** } else if (methods[i].getName().startsWith("say")) { //call method System.out.println(methods[i].invoke(object)); } } } catch (Exception ex) { ex.printStackTrace(); } } private String getClassName() { //Do appropriate stuff here to find out the classname return "com.main.MyClass"; } public static void main(String[] args) throws Exception { new Main().loadClass(); } } ``` My question is how to invoke method with parameters and passing its value? also getting the return value and its type.

Original source