Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection to invoke method on field

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).

like image 411
priojewo Avatar asked Apr 08 '14 06:04

priojewo


People also ask

How do you access a private field using a reflection?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.

How do you call a static method using reflection?

In the example above, we first obtain the instance of the class we want to test, which is GreetingAndBye. After we have the class instance, we can get the public static method object by calling the getMethod method. Once we hold the method object, we can invoke it simply by calling the invoke method.


1 Answers

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);
like image 169
Morfic Avatar answered Oct 08 '22 17:10

Morfic