how to pass multiple parameters to a method in java reflections

dynamic, java, parameter-passing, reflection

Solution

Hi all i have found the solution to the above question. below is the sample code snippet.

package reflections;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionTest {
    public void method1(String str, int number) {
        System.out.println(str + number);
    }

    public void method1(String str) {
        System.out.println(str);
    }

    public void method1() {
        System.out.println("helloworld");
    }

    public static void main(String[] args) throws ClassNotFoundException,
            InstantiationException, IllegalAccessException,
            NoSuchMethodException, SecurityException, IllegalArgumentException,
            InvocationTargetException {
        // Step 1) Make an object array and store the parameters that you wish
        // to pass it.
        Object[] obj = {};// for method1()
        // Object[] obj={"hello"}; for method1(String str)
        // Object[] obj={"hello",1}; for method1(String str,int number)
        // Step 2) Create a class array which will hold the signature of the
        // method being called.
        Class<?> params[] = new Class[obj.length];
        for (int i = 0; i < obj.length; i++) {
            if (obj[i] instanceof Integer) {
                params[i] = Integer.TYPE;
            } else if (obj[i] instanceof String) {
                params[i] = String.class;
            }
            // you can do additional checks for other data types if you want.
        }

        String methoName = "method1"; // methodname to be invoked
        String className = "reflections.ReflectionTest";// Class name
        Class<?> cls = Class.forName(className);
        Object _instance = cls.newInstance();
        Method myMethod = cls.getDeclaredMethod(methoName, params);
        myMethod.invoke(_instance, obj);
    }
}

I hope this will help others too.

Problem

Hi i am using reflections to achieve something. I have been given class name, method name of that class and parameter values that needs to be passed to that method in a file(Take any file. Not a constraint). I have to call that method with the parameters. This methods do not return anything. There is a huge list of methods in this classes and parameter list of each varies. E.g: `method1(String, String, int, boolean)` `method1(String, int, boolean)` and likewise i have different permutations and combinations. So how can i achieve this. I have tried hard coding things with different switch clauses but it is a real overhead and risky thing to maintain. Can we dynamically do this thing, like on the fly read the method name and its parameter from the file and call it. Any small code snippet will be helpful. TIA.

Original source