jeudi 4 février 2016

How to call any methods having any number of parameter and any datatype in Java

I want to create one method which can any method with any number of parameter and of any data type.

For eg. I want to call following all methods dynamically void method1(int x, int y) void method2(int x, String y) void method3(Float x, Long y, String z)


I am using reflection to do so. Now I stucked that how to pass parameters to these methods during invoking this dynamic method. How far I did....

    MyClass myClass = new MyClass();
    Class<?> c = myclass.getClass();
    Method[] m = c.getMethods();
    int i = 0;
    Object [] obj;   // obj contains values to be passed
    for(Method method : m)
    {
        if("methodX".equals(method.getName()))
        {
            break;
        }
        i++;
    }
    Method myMethod = m[i];
    myMethod.invoke(myClass, obj); //this is not working

How can I invoke myMethod?

While invoking method, I am getting error "incorrect number of parameters"





Aucun commentaire:

Enregistrer un commentaire