你可以使用反射
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.
请注意,Class#getMethod(..)仅适用于公共方法.但在这种情况下,equals()和hashCode()必须是公共的.取决于该算法需要针对其他方法进行更改.