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


i'm trying invoke method unknown number of parameter (when being invoked) using reflection.

i've seen number of similar questions here, e.g. how invoke method variable arguments in java using reflection? or how invoke method in java using reflection these use methods names: reflectionexample.class.getmethod("test", int.class) not i'm trying do.

please see sample code below:

/* arbitary class extending 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();     }  }  /* class extending 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 determine how process result */ public class resolver{    public void doreflect(mybaseclass obj){       method[] methods = obj.getmethods();       (method m : methods){        /*         * invoke works fine myclass.method1         * throws exception myotherclass.method2 or myotherclass.method3         */         /* many andy turner assistance.           i've edited original post show recommended solution */        class<?>[] klasses = m.getparametertypes();         object[] oobjects = new object[klasses.length];         (int x =0; x<klasses.length; x++)             oobjects[x] = klasses[x].newinstance();         object value = m.invoke(myclass, oobjects)         // ... stuff      }   } } 

i appreciate give me on this.

thanks in advance.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -