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



>有没有办法找出一个类是否覆盖了equals()hashCode()

您可以使用反射

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; }
     */
}

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

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

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

若要检查是否在类中声明了方法,可以使用以下代码。

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

在这里,您可以找到声明类的名称。

因此,使用子类中的代码进行检查,以检查是否等于或hasCode方法。如果声明的类名与所需的类相同,则匹配

最新更新