假设我有以下代码:
abstract class MyStream
{
public abstract Iterable<Integer> getIterable();
public MyStream append(final int i)
{
return new MyStream()
{
@Override
public Iterable<Integer> getIterable()
{
return cons(/*outer class's*/getIterable(), i);
}
};
}
public static Iterable<Integer> cons(Iterable<Integer> iter, int i) { /* implementation */ }
}
Run Code Online (Sandbox Code Playgroud)
如何getIterable从内部类中引用具有相同名称的外部类?
MyStream.this应该指向这里的内部类吧?如何显示具有相同名称的外部类?
如果MyStream.this从匿名类调用它将指向外部类,因此下面的代码应该按预期工作:
return const(MyStream.this.getIterable(), i);
Run Code Online (Sandbox Code Playgroud)
(如果没有,你会得到一个StackOverflowError).
它起作用的原因是匿名类是一个内部类.
打印的简化示例outer 1:
public static void main(String args[]) {
MyClass c = new MyClass() {
@Override public String get() { return "outer"; }
};
System.out.println(c.append(1).get());
}
static abstract class MyClass {
public abstract String get();
public MyClass append(final int i) {
return new MyClass() {
@Override public String get() {
return cons(MyClass.this.get(), i);
}
};
}
public static String cons(String iter, int i) { return iter + " " + i; }
}
Run Code Online (Sandbox Code Playgroud)