Implement equals () using JDK dynamic proxies

For the first time, I have to implement my own proxy classes using the standard JDK Dynamic Proxy. It works quite well, with one exception: method equals(...).

Suppose we have a simple interface like this, which we want a 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 server, the method is equals(...)no longer symmetrical:

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 stated in this article .

My question is: if I want all four “equal” cases to deliver true, what is the best (that is, the safest and least intrusive) way to do this?

+4
2

equals();

public final boolean equals(final Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (! (obj instanceof MyInterface)) // neither a Proxy nor a MyImplementation
    return false;

    MyInterface other = (MyInterface) obj;
    if (this.getID() == null) {
       if (other.getID() != null) {
               return false;
       }
    } else if (!this.getID().equals(other.getID())) {
      return false;
    }
    return true;
}

getID() . .

0

, . :

, , -.

JAVA , Proxies . ...

, , : JAVA , , hashcode equals.

"" . , - . JAVA .

, Proxy-Wrapping equals/hashcode. , .

, -, - . - :

Map<Proxy, Original> map;

JAVA. , , Set-Implementations, equals hashcode. JAVA Proxies, .

Java- . , Java Proxies, , .

( ) - - JAVA. : - hashcode/equals, .

0

All Articles