这里的诀窍是知道内部类是如何工作的。它本质上只是一个“普通”的静态类,但其构造函数隐式获取对封闭类的引用。所以这:
public class TopLevel {
public void go() {
new Inner().bar();
}
public void foo() { }
public class Inner {
public void bar() {
TopLevel.this.foo();
}
}
}
相当于:
public class TopLevel {
public void go() {
new Inner(this).bar(); // explicitly passing in "this"
}
public void foo() { }
public static class Inner {
private final TopLevel parent; // note that we have this new field
public Inner(TopLevel parent) { // note this new constructor
this.parent = parent;
}
public void bar() { // we use the explicit reference instead
parent.foo(); // of the implicit TopLevel.this
}
}
}
因此,综上所述,将内部类重构为顶级类的方法是添加一个引用UpperClass
实例的显式字段,并将此引用传递给NestedClass
构造函数。换句话说,就像第二个代码片段而不是第一个。