mercredi 23 octobre 2019

How to access nested java member variable value using string with dot operator

If we have class like

class A{
    private B b;

    //getter & setter
}

class B{
    private C c;
    //getter and setter
}

class C{
    private String d="hello";
    private Map<String,String> e = new HashMap<>();
//getter and setter
}

if we want to write a function like below do we have any readily available framework?

public void test( A a){
    String result = getValue(a, "b.c.d");//result should be equal to "hello"
}

To make complicated the framework should also be able to handle fetch like:

String result = getValue(a, "b.c.e.f");//result should be able to fetch value from Map 'e' for key 'f'

I know if we can serialize A to JSON then I think we have some readily available API, but is there any way without serializing to JSON, we can still use reflection to do this lookup?





Aucun commentaire:

Enregistrer un commentaire