当从实例方法返回没有引用其封闭类的匿名类时,它具有对此的引用。为什么?
当从实例方法返回没有引用其封闭类的匿名类时,它具有对 的引用。为什么?this
请考虑以下代码:
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]);
}
}
这是输出:
Number of fields static context: 0
Number of fields instance context: 1
Field from instance context: final so.SOExample so.SOExample$2.this$0
每个方法虽然看似调用相同的代码,但正在执行不同的操作。在我看来,实例方法返回的是嵌套类,而静态方法返回的是静态嵌套类(作为静态成员,它显然不能引用 )。this
鉴于没有引用封闭类的事实,我看不到这样做的好处。
幕后发生了什么?