如何在非静态内部类的另一个实例中引用外部类?

Kri*_*mbe 14 java syntax reference inner-classes

我正在使用Apache Commons EqualsBuilder为非静态Java内部类构建equals方法.例如:

import org.apache.commons.lang.builder.EqualsBuilder;

public class Foo {
    public class Bar {
        private Bar() {}

        public Foo getMyFoo() {
            return Foo.this
        }

        private int myInt = 0;

        public boolean equals(Object o) {
            if (o == null || o.getClass() != getClass) return false;

            Bar other = (Bar) o;
            return new EqualsBuilder()
                .append(getMyFoo(), other.getMyFoo())
                .append(myInt, other.myInt)
                .isEquals();
        }
    }

    public Bar createBar(...) {
        //sensible implementation
    }

    public Bar createOtherBar(...) {
        //another implementation
    }

    public boolean equals(Object o) {
        //sensible equals implementation
    }
}
Run Code Online (Sandbox Code Playgroud)

除了声明方法之外,有没有语法可以引用它otherFoo参考getMyFoo()?喜欢的东西other.Foo.this(哪个不起作用)?

小智 6

没有.

最好的方法可能就是你的建议:在你的内部类中添加一个getFoo()方法.