【发布时间】:2015-08-09 21:39:40
【问题描述】:
有史以来第一次,我必须使用标准的 JDK 动态代理来实现我自己的代理类。它工作得相当好,除了一个细节:equals(...) 方法。
假设我们有一个像这样的简单接口,我们想要代理它:
public interface MyInterface {
public String getID();
public void setID(String id);
}
...我们的实现看起来像这样(标准 Java Bean 生成 hashCode() 和 equals):
public class MyImplementation implements MyInterface {
private String id;
public String getID() { return this.id; }
public void setID(String id) { this.id = id; }
// hash code & equals generated by eclipse
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.databaseId == null ? 0 :
this.id.hashCode());
return result;
}
public final boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
MyImplementation other = (MyImplementation) obj;
if (this.databaseId == null) {
if (other.databaseId != null) {
return false;
}
} else if (!this.databaseId.equals(other.databaseId)) {
return false;
}
return true;
}
}
问题是,当我创建代理时,equals(...) 方法不再是对称的:
original.equals(original); // true
proxy.equals(original); // true, as the proxy forwards the call to the wrapped object
original.equals(proxy); // false
proxy.equals(proxy); // false
this article 中也对此进行了讨论。
我的问题是:如果我希望所有四个“相等”的案例都交付 true,那么最好的(即最安全和最少干扰的)方法是什么?
【问题讨论】:
-
您必须根据接口的成员方法来实现接口实现的
equals方法。看看List#equals(Object)是如何做到的(javadoc 中是如何描述的)。
标签: java proxy equals dynamic-proxy