java - Using reflection to invoke method on field -


my code looks following:

class myobject {      myfield f = new myfield();  }  class myfield {     public void greatmethod(); } 

is there way invoke greatmethod() using reflection on object of class myobject?

i tried following:

field f = myobject.getclass().getdeclaredfield("f"); method mymethod = f.getdeclaringclass().getdeclaredmethod("greatmethod", new class[]{}); mymethod.invoke(f); 

but instead trying call greatmethod() on myobject directly , not on field f in it. there way achieve without need modify myobject class (so implement method calls appropriate method on f).

you close yourself, need declared method , invoke on instance of field containted within object instance, instead of field, below

    // obtain object instance     myobject myobjectinstance =  new myobject();      // field definition     field fielddefinition = myobjectinstance.getclass().getdeclaredfield("f");      // make accessible     fielddefinition.setaccessible(true);      // obtain field value object instance     object fieldvalue = fielddefinition.get(myobjectinstance);      // declared method     method mymethod =fieldvalue.getclass().getdeclaredmethod("greatmethod", new class[]{});      // invoke method on instance of field yor object instance     mymethod.invoke(fieldvalue); 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -