如果上下文是静态的,则匿名类是静态的。例如在静态方法中。
如果存在非静态上下文,则匿名类是非静态的,无论您是否需要它是非静态的。如果不使用非静态上下文,编译器不够聪明,无法将类设为静态。
在此示例中,创建了两个匿名类。静态方法中的一个没有对外部类的引用,就像一个静态嵌套类。
注意:这些类仍然被称为“Inner”并且不能有静态成员,即使它们没有对 Outer 类的引用。
import java.util.Arrays;
public class Main {
Object o = new Object() {
{
Object m = Main.this; // o has a reference to an outer class.
}
};
static Object O = new Object() {
// no reference to Main.this;
// doesn't compile if you use Math.this
};
public void nonStaticMethod() {
Object o = new Object() {
{
Object m = Main.this; // o has a reference to an outer class.
}
};
printFields("Anonymous class in nonStaticMethod", o);
}
public static void staticMethod() {
Object o = new Object() {
// no reference to Main.this;
// doesn't compile if you use Math.this
};
printFields("Anonymous class in staticMethod", o);
}
private static void printFields(String s, Object o) {
System.out.println(s + " has fields " + Arrays.toString(o.getClass().getDeclaredFields()));
}
public static void main(String... ignored) {
printFields("Non static field ", new Main().o);
printFields("static field ", Main.O);
new Main().nonStaticMethod();
Main.staticMethod();
}
}
印刷
Non static field has fields [final Main Main$1.this$0]
static field has fields []
Anonymous class in nonStaticMethod has fields [final Main Main$3.this$0]
Anonymous class in staticMethod has fields []