For the first time ever, I have to implement my own proxy classes using the standard JDK Dynamic Proxy. It works fairly well, except for one detail: the equals(...)
method.
Let's assume that we have a simple Interface like this, which we want to proxy:
public interface MyInterface {
public String getID();
public void setID(String id);
}
... and our implementation looks like this (standard Java Bean with generated hashCode()
and 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;
}
}
The problem is, that when I create a proxy, the equals(...)
method is no longer symmetric:
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 is also discussed in this article.
My question is: if I want all four "equals" cases to deliver true
, what's the best (i.e. safest and least intrusive) way to go about it?