我有下面的代码。我想获得外部类对象,我使用它创建了内部类对象inner。我该怎么做呢?
public class OuterClass {
public class InnerClass {
private String name = "Peakit";
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
InnerClass inner = outer.new InnerClass();
// How to get the same outer object which created the inner object back?
OuterClass anotherOuter = ?? ;
if(anotherOuter == outer) {
System.out.println("Was able to reach out to the outer object via inner !!");
} else {
System.out.println("No luck :-( ");
}
}
}
编辑:嗯,有些人建议通过添加一个方法来修改内部类:
public OuterClass outer() {
return OuterClass.this;
}
但是如果我没有修改内部类的控制,那么(只是确认一下)我们是否有其他方法从内部类对象中获得相应的外部类对象?