Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a class has overridden equals and hashCode

Tags:

java

Is there a way to find out if a class has overriden equals() and hashCode() ?

like image 314
Jabir Avatar asked Feb 26 '14 04:02

Jabir


People also ask

Does == check hashCode?

== is checking for reference equality, the hashCode() method is cheking the hashCode of the instance (however you have decided it should be calculated), the fact your hashcodes are the same just means that whatever your hashCode method is doing is calculating the same hasCode for both objects, which is what it should ...

How do you identify whether the method is overridden or not?

getMethod("myMethod"). getDeclaringClass(); If the class that's returned is your own, then it's not overridden; if it's something else, that subclass has overridden it.

What if hashCode and equals are not overridden?

Overriding only equals() method without overriding hashCode() causes the two equal instances to have unequal hash codes, which violates the hashCode contract (mentioned in Javadoc) that clearly says, if two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two ...

Is it mandatory to override hashCode and equals method?

You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object. hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.


2 Answers

You can use reflection

public static void main(String[] args) throws Exception {
    Method method = Bar.class.getMethod("hashCode" /*, new Class<?>[] {...} */); // pass parameter types as needed
    System.out.println(method);
    System.out.println(overridesMethod(method, Bar.class));
}

public static boolean overridesMethod(Method method, Class<?> clazz) {
    return clazz == method.getDeclaringClass();
}

class Bar {
    /*
     * @Override public int hashCode() { return 0; }
     */
}

will print false if the hashCode() is commented out and true if it isn't.

Method#getDeclaringClass() will return the Class object for the class where it is implemented.

Note that Class#getMethod(..) works for public methods only. But in this case, equals() and hashCode() must be public. The algorithm would need to change for other methods, depending.

like image 108
Sotirios Delimanolis Avatar answered Sep 19 '22 18:09

Sotirios Delimanolis


to check if a method is declared in your class you can use the following code.

System.out.println(C.getMethod("yourMethod").getDeclaringClass().getSimpleName());

here you can find the name of the declaring class.

So check using the code in your subclass to check if equals or hasCode method. And match if the declaring class name is same as your desired class

like image 27
stinepike Avatar answered Sep 18 '22 18:09

stinepike