Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement equals method for Java anonymous class properly?

In this post I suggested a solution that uses interface and anonymous class. However, there is one thing to be implemented: the hashCode and equals method.

However I found it is hard to implement equals for anonymous class that implements an interface. In that example the interface is Pair<L,R>, and a factory method Pairs.makePair will return an anonymous implementation for it. Suppose I added an equals implementation. The user may implement their own Pair<L,R> classes with a different equals code, therefore the call userobj.equals(makepairobj) will enter their code, and makepairobj.equals(userobj) will enter my code. Because I have no control of their code, it is hard to make sure equals to be symmetric, which is required for a good implementation.

I believe this problem is common for other cases, so I would like to know how this issue being address generally?

EDIT: In typical class, the implementation of equals will check the parameter type to make sure it is the same as its own. This guarantee only the implementing code will be called to compare the objects. However, the anonymous class do not have a name and cannot check the type with instanceof. What I can do is make sure it is an instance of the implementing interface/class. Which is not enough to prevent the above scenario.

like image 975
Earth Engine Avatar asked Oct 14 '25 06:10

Earth Engine


1 Answers

You can use this.getClass() (with either == or isAssignableFrom()) to compare the types.

Edit

As in:

public boolean equals(Object obj) {
    if (getClass() == obj.getClass()) {
        // do whatever
    }
    return false;
}
like image 136
Dmitri Avatar answered Oct 16 '25 20:10

Dmitri