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
Every non-static inner class maintains an invisible ivar that holds a reference to the outer class that it was instantiated for. That’s what
this$0is.Change InnerClass to
public static classand see the difference.For clarity, Oracle recommends this terminology:
http://download.oracle.com/javase/tutorial/java/javaOO/nested.html
===
In a method of the inner class, you can say:
or
This special variant of this –
OuterClass.this– is accessing thethis$0ivar – it will return theOuterClassinstance. Note that this is different than using the regularthisinside anInnerClassmethod, which will return the currentInnerClassinstance.===
I’m unclear what you are trying to do, so I can’t recommend how to achieve what you want.