从匿名类访问父类时解决歧义

时间:2015-03-31 14:08:48

标签: java anonymous-class

我最近碰到了这样的事情......

public final class Foo<T>
implements Iterable<T> {

    //...

    public void remove(T t) { /* banana banana banana */ }

    //...

    public Iterator<T> Iterator {
        return new Iterator<T>() {

            //...

            @Override
            public void remove(T t) {
                // here, 'this' references our anonymous class...
                // 'remove' references this method...
                // so how can we access Foo's remove method?           
            }

            //...

        };
    }
}

有什么方法可以做我想要保持这个匿名课程的方法吗?或者我们必须使用内部类或其他东西吗?

3 个答案:

答案 0 :(得分:9)

要访问封闭类中的remove,您可以使用

...
    @Override
    public void remove(T t) {
        Foo.this.remove(t);         
    }
...

相关问题:Getting hold of the outer class object from the inner class object

答案 1 :(得分:7)

您可以使用Classname.this访问封闭类。所以在你的例子中:

public void remove(T t){
    Foo.this.remove(t);
}

答案 2 :(得分:2)

Foo.this.remove(t)会为你做到这一点。

相关问题