zeal
zeal

Reputation: 475

Java Reflection to read inner class values

I have created a java class something like below:

public class TopNode {
  public Child1 c1;
  public Child2 c2;

public static class Child1 {
  public String s1;
  public String s2;
  }

public static class Child2 {
  public String s3;
  public String s4;
  }
}

This is class is used to read the JSON response using Gson. Something like below:

static Class<?> readJson(Class<?> obj) throws Exception {
Gson gson = new Gson();
.....
.....
return gson.fromJson(json, obj.getClass());
}

I am reading json response using above method and storing it into the object.

TN_CONFIG

From this object, I am trying to access the inner class fields and their values, but getting null value only. Example:

....
....
Field f = TN_CONFIG.getClass().getDeclaredField("c1")
   .getType().getDeclaredField("s1");
System.out.println("S1: " + f.get(new TopNode.Child1());
....

Can someone help to find where I'm going wrong here?

Upvotes: 1

Views: 651

Answers (2)

i.bondarenko
i.bondarenko

Reputation: 3572

I think you have issue in reflection code. You get value from new "empty" Child1 f.get(new TopNode.Child1())

Have a look at the code:

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
    Child1 c1 = new Child1("value1", "value2");
    TopNode node = new TopNode(c1, new Child2("value3", "value4"));
    Field f = node.getClass().getDeclaredField("c1")
            .getType().getDeclaredField("s1");
    System.out.println("S1: " + f.get(c1));
}

Output:

S1: value1

Update, could you try follwing code to get the value:

    Field fieldC1 = TN_CONFIG.getClass().getDeclaredField("c1");
    Object objectC1 = fieldC1.get(TN_CONFIG);
    Field fieldS1 = objectC1.getClass().getDeclaredField("s1");
    Object valueS1 = fieldS1.get(objectC1);
    System.out.println("Value S1 = " +  valueS1);

Upvotes: 3

user85421
user85421

Reputation: 29710

Not sure if I understood the problem, but lets try with a simpler sample:

class TopNode {
    public Child1 c1;

    public static class Child1 {
        public String s1;
    }
}

Assuming TN_CONFIG is an instance of TopNode (or any other class that has a c1 which itself has a s1), first we need to get the c1 instance like in

Field fieldC1 = TN_CONFIG.getClass().getDeclaredField("c1");
Object child1 = fieldC1.get(TN_CONFIG);

and then we can can get the field value inside it

Field fieldS1 = fieldC1.getType().getDeclaredField("s1");
Object value = fieldS1.get(child1);

Note: this should also work if Child1 is not a nested class.

Note2: fieldC1.getType() can be replaced by child1.getClass()

Upvotes: 2

Related Questions