如何检查类是否覆盖了equals和hashCode

Jab*_*bir 9 java

有没有办法找出如果一个类重写equals()hashCode()

Sot*_*lis 21

你可以使用反射

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; }
     */
}
Run Code Online (Sandbox Code Playgroud)

false如果hashCode()被注释掉,true如果没有,则打印.

Method#getDeclaringClass()将返回Class实现它的类的对象.

请注意,仅Class#getMethod(..)适用于public方法.但是,在这种情况下,equals()hashCode()必须public.取决于该算法需要针对其他方法进行更改.