更新时间:2023-02-05 21:45:14
你可以使用反射
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; }
*/
}
将打印 false
如果 hashCode()
被注释掉,为真
,如果不是。
will print false
if the hashCode()
is commented out and true
if it isn't.
方法#getDeclaringClass()
将返回该类所在的 Class
对象实施。
注意 Class#getMethod(..)
仅适用于 public
方法。但在这种情况下,等于()
和 hashCode()
必须是 public
。该算法需要根据其他方法进行更改。
Note that Class#getMethod(..)
works for public
methods only. But in this case, equals()
and hashCode()
must be public
. The algorithm would need to change for other methods, depending.