When an anonymous class with no references to its enclosing class is returned from an instance method, it has a reference to this
. Why?
Consider the following code:
package so;
import java.lang.reflect.Field;
public class SOExample {
private static Object getAnonymousClassFromStaticContext() {
return new Object() {
};
}
private Object getAnonymousClassFromInstanceContext() {
return new Object() {
};
}
public static void main(String[] args) throws NoSuchFieldException, SecurityException {
Object anonymousClassFromStaticContext = getAnonymousClassFromStaticContext();
Object anonymousClassFromInstanceContext = new SOExample().getAnonymousClassFromInstanceContext();
Field[] fieldsFromAnonymousClassFromStaticContext = anonymousClassFromStaticContext.getClass().getDeclaredFields();
Field[] fieldsFromAnonymousClassFromInstanceContext = anonymousClassFromInstanceContext.getClass().getDeclaredFields();
System.out.println("Number of fields static context: " + fieldsFromAnonymousClassFromStaticContext.length);
System.out.println("Number of fields instance context: " + fieldsFromAnonymousClassFromInstanceContext.length);
System.out.println("Field from instance context: " + fieldsFromAnonymousClassFromInstanceContext[0]);
}
}
This is the output:
Number of fields static context: 0
Number of fields instance context: 1
Field from instance context: final so.SOExample so.SOExample$2.this$0
Each method, although seemingly calling the same code, is doing something different. It looks to me that the instance method is returning a nested class, whereas the static method is returning a static nested class (as a static member, it obviously can't have a reference to this
).
Given the fact that there's no reference to the enclosing class, I can't see the benefit in this.
What's going on behind the scenes?