dimanche 19 juin 2022

java reflection on different argument number

Is it possible to pass different number of arguments to a dynamic reflection method??

I have N classes, for instance

class A { method_A(T arg1, S arg2){}}
class B { method_B(T arg1){}}
class C //... and so on

I try to build a function able to invoke any method in any class

 main(){
   Object[] args = {"arg1", "arg2"};
   foo(new A(), "method_A", args);
 }
 foo(Object obj, String objectiveMethod, Object[] params){
   Method[] allMethods = obj.getClass().getDeclaredMethods();
   for(Method method: allMethods){
     //find the objective method, irrelevant to the question
     if(objectiveMethod.equals(method.getName())){
       method.invoke(obj, params); // Here throws IllegalArgumentException: wrong number of arguments
     }
   }
 }

I can easily retrieve the amount of arguments Method.getParameterCount(), but i can't figure out how to dynamically pass N number of arguments retrieved from Object[] args;.

I thought that MethodAccessor.invoke(Object obj, Object[] args) could handle this (because of Object[] args) but it doesn't work and throws

IllegalArgumentException: wrong number of arguments

Could you help me figure out any way to achieve that? Or it's impossible?

--edit--

 f(){
   A aObj = new A(); C cObj = new C();
   Object[] args = {"arg1", "arg2"};
   Object[] argsC = {"arg1", 2, new B()};
   aObj.method_A(args[0], args[1]); // works fine
   ...
   /* It doesn't matter which type of object they are, they still have known of it's type without casting*/
   method.invoke(aObj, args[0], args[1]); // works fine
   method.invoke(aObj, args); // doesn't work, wrong number of args.


   methodC.invoke(cObj, args...?);// 3 args dynamically
 }




Aucun commentaire:

Enregistrer un commentaire