Using reflection to invoke method on field

priojewo picture priojewo · Apr 8, 2014 · Viewed 9.8k times · Source

My code looks like the following:

class MyObject {

    MyField f = new MyField();

}

class MyField {
    public void greatMethod();
}

Is there a way to invoke the greatMethod() using reflection on a object of the class MyObject?

I tried the following:

Field f = myObject.getClass().getDeclaredField("f");
Method myMethod = f.getDeclaringClass().getDeclaredMethod("greatMethod", new Class[]{});
myMethod.invoke(f);

But instead it is trying to call greatMethod() on my myObject directly and not on the field f in it. Is there a way to achieve this without need to modify the MyObject class (so that it would implement a method which calls the appropriate method on f).

Answer

Morfic picture Morfic · Apr 8, 2014

You were close yourself, you just need to get the declared method and invoke it on the instance of the field that is containted within your object instance, instead of the field, like below

    // obtain an object instance
    MyObject myObjectInstance =  new MyObject();

    // get the field definition
    Field fieldDefinition = myObjectInstance.getClass().getDeclaredField("f");

    // make it accessible
    fieldDefinition.setAccessible(true);

    // obtain the field value from the object instance
    Object fieldValue = fieldDefinition.get(myObjectInstance);

    // get declared method
    Method myMethod =fieldValue.getClass().getDeclaredMethod("greatMethod", new Class[]{});

    // invoke method on the instance of the field from yor object instance
    myMethod.invoke(fieldValue);