Raf*_*ter 5 java equality inner-classes
我目前想知道是否有一种equals在Java 中实现非静态内部类的方法的好方法.我基本上是Foo一个Bar像这样的内部类的类:
public class Foo {
private final String foo; // constructor omitted
public /* non-static */ class Bar {
private final String bar; // constructor omitted
@Override
public boolean equals(Object other) {
return other != null && other.getClass() == getClass()
&& ((Bar) other).bar.equals(this.bar)
&& Foo.this.equals(Foo.((Bar) other)); // Will, of course, not compile.
}
}
@Override
public boolean equals(Object other) {
return other != null && other.getClass() == getClass()
&& ((Foo) other).foo.equals(foo);
}
}
Run Code Online (Sandbox Code Playgroud)
我的类在现实中要复杂得多,我想Foo#equals从内部重用该方法Bar#equals以节省大量代码.我现在正在考虑将"内部阶级关系"明确化,以便能够引用"外部"类.但是,我必须手动添加访问器方法,我想避免这种情况.我无法摆脱应该采用Java方法做到这一点的感觉.