0

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"

Kartik
  • 11
  • 2
  • 1
    Possible duplicate of [How do I invoke a Java method when given the method name as a string?](http://stackoverflow.com/questions/160970/how-do-i-invoke-a-java-method-when-given-the-method-name-as-a-string) – scana Feb 04 '16 at 09:52
  • Check the method name as well as the parameter types. Apache Commons Lang has some utility classes that help with this. Still, IMO the main question is: _what are you trying to achieve with this?_ – Thomas Feb 04 '16 at 09:55

1 Answers1

0

Try myMethod.invoke(subject, obj), subject being an instance you want to call the method on.

Grogi
  • 2,099
  • 17
  • 13
  • Passing `obj` would only work if the method took only one parameter of type `Object[]`. – Thomas Feb 04 '16 at 09:56
  • @Thomas - it works, just validated it... `invoke` takes two parameters - subject and array of arguments. If you want to pass an array as an argument, you'd need to create an array with one element in it - an array... Like that: `MyClass.class.getMethod("a", Object[].class).invoke(subject, new Object[] { obj });` – Grogi Feb 04 '16 at 10:00