【发布时间】:2010-10-20 07:07:57
【问题描述】:
如果我有一个内部类的实例,我如何从不在内部类中的代码访问外部类?我知道在内部类中,我可以使用Outer.this 来获取外部类,但是我找不到任何外部获取方式。
例如:
public class Outer {
public static void foo(Inner inner) {
//Question: How could I write the following line without
// having to create the getOuter() method?
System.out.println("The outer class is: " + inner.getOuter());
}
public class Inner {
public Outer getOuter() { return Outer.this; }
}
}
【问题讨论】:
-
您能解释一下您要解决的问题吗?还是这是学术?
-
学术,主要是。当我想出一个答案时,我遇到了它:stackoverflow.com/questions/763359/… 我给出了两个答案,一个是按照 OP 的要求使用我上面使用的相同解决方法(getOuter() 方法)。但是在我的另一个答案(已被投票的那个)中,我说要以不同的方式设计它,这样就没有必要了。但我仍然很好奇是否有可能做到这一点。
-
您提供的示例是此问题的最佳答案。