Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflecting nested anonymous classes

Why does this code return "class java.lang.Object" ?

Object a = new Object() {
  public Object b = new Object(){
    public int c;
  };
};

System.out.println(a.getClass().getField("b").getType());

Why does the inner-inner type get lost? How can I reflect the c field ?

Edit:

This one works (as pointed out in some answers):

a.getClass().getField("b").get(a) ...

But then I have to invoke a getter, is there any way to reflect c with only reflection meta data?

like image 266
Marcus Avatar asked Jun 21 '26 12:06

Marcus


1 Answers

Because b is declared as Object:

public Object b = ...;

There is a distinction between type of variable (static type) and type of the object referenced by that variable (runtime type).

Field.getType() returns static type of the field.

If you want to get runtime type of the object referenced by the field, you need to access that object and call getClass() on it (since a is declared as Object and therefore b is not visible as its member you have to use reflection to access it):

System.out.println(
     a.getClass().getField("b").get(a).getClass());

UPDATE: You can't reflect c without accessing the instance of object containing it. That's why these types are called anonymous - a type containing c has no name, so that you can't declare field b as a field of that type.

like image 72
axtavt Avatar answered Jun 23 '26 00:06

axtavt