lundi 8 février 2016

Java reflection how to invoke a method with unknown number of arguments?

I'm trying to invoke a method with an unknown number of parameter (when being invoked) using reflection.

I've seen a number of similar questions here, e.g. How to invoke method with variable arguments in java using reflection? or How to invoke a method in java using reflection but these use methods names: ReflectionExample.class.getMethod("test", int.class) which is not what I'm trying to do.

Please see the sample code below:

/* an arbitary class extending a base class */
public class MyClass extends MyBaseClass {

    private String message = "";

    public void setMessage(String value){
        this.message = value;
    }

    public String getMessage(){
        return this.message;
    }

    public String method1(){
        /* blah blah */
        return getMessage();
    }
 }

/* another class extending the arbitary class */
public class MyOtherClass extends MyClass {

    public List<T extends MyClass> method2(SomeEnum enumValue, Object otherValue){
        List<MyClass> list = new ArrayList<MyClass>();
        MyClass c = new MyClass();
        c.setMessage("first message: " + enumValue.toString());
        list.add(c);
        MyClass c = new MyClass();
        c.setMessage("second message: " + otherValue.toString());
        list.add(c);
        return list;
    }

    public Object method3(Object param1, Object param2, Object param3){
        /* ... */
    }
}

/* use reflection to determine how to process the result */
public class Resolver{

  public void DoReflect(MyBaseClass obj){

     Method[] methods = obj.getMethods();

     for (Method m : methods){
       /*
        * this invoke works fine for MyClass.method1
        * but throws an exception for MyOtherClass.method2 or MyOtherClass.method3
        */
       Object value = m.invoke(obj, new Object[] {});

       // ... do some stuff
     }
  }
}

I would very much appreciate any help you could give me on this.

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire