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

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

你可以使用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; } */ } 

如果hashCode()被注释掉,则打印为false如果不注释,则打印为true

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

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

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

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

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

因此,请检查子类中的代码以检查是否为equals或hasCode方法。 如果声明的类名与所需的类相同,则匹配