How to check if a class has overridden equals and hashCode

前端 未结 2 590
囚心锁ツ
囚心锁ツ 2021-01-02 09:05

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

相关标签:
2条回答
  • 2021-01-02 09:57

    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

    0 讨论(0)
  • 2021-01-02 10:03

    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.

    0 讨论(0)
提交回复
热议问题