I'm running into a strange result here and am not sure if it is a bug in Java or it is expected behaviour. I have an inner class on which I've used reflection to get the declared fields (class.getDeclaredFields()). However, when I loop over the list of fields and check the individual types, the "this" field returns the outerclass and not the inner class.
Is this expected behaviour? It seems quite odd to me.
Ex:
import java.lang.reflect.Field;
public class OuterClass {
public class InnerClass{
public String innerClassString;
public InnerClass innerClass;
}
public static void main(String[] args) {
// print the fields of the inner class
for( Field field : OuterClass.InnerClass.class.getDeclaredFields())
System.out.println( field.getName() + " ::: " + field.getType());
}
}
Output:
innerClassString ::: class java.lang.String
innerClass ::: class OuterClass$InnerClass
this$0 ::: class OuterClass
I expected this$0 to be of type OuterClass.InnerClass.
Is this a Java bug? Is there anyway to workaround this unexpected behaviour?
Thanks,
Eric