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.取决于该算法需要针对其他方法进行更改.