Skip to content

Invoke nested deepobject method via reflection

Is it possible to invoke nested method inside nested object from real object using reflection? Something like this

val fieldDefinition = chatClient.javaClass.getDeclaredField("class1")
  .type.getDeclaredField("class2").type.getDeclaredField("class3")

Real object i have is chatClient and i want to invoke method of class3, which i cannot obtain directly but via class1 path.

Answer

You can have a logic of fetching nested fields in a function inside a for loop , so that you can avoid code duplication.

Whole code example in java:

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class Class1 {
    Class2 class2 = new Class2();

}
class Class2 {
    Class3 class3 = new Class3();
}
class Class3 {
    Class4 class4 = new Class4();
}
class Class4 {

    public void display(){
        System.out.println("Hello World");
    }

}


public class Test {

    static Object getFieldValue(String fieldPath ,Object object) throws NoSuchFieldException, IllegalAccessException {
        String[] pathList = fieldPath.split("\.");
        for(String path : pathList){
            Field field = object.getClass().getDeclaredField(path);
            field.setAccessible(true);
            object = field.get(object);
        }
        return object;
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class1 class1Object = new Class1();
        Object object = getFieldValue("class2.class3.class4", class1Object);

        Method method = object.getClass().getMethod("display");
        method.invoke(object);

    }
}

Here fieldPath in getFieldValue means path of the nested field object.