给定以下代码:
class A{
int i;
int hashcode(){
. . .
}
}
确切地说,给定A
的对象a
,怎么能说继承自Object
类的hashcode()
在A
类中被重写呢。
a.getClass().getDeclaringClass()
正在返回Object
类。我希望它输出A
。
这应该适合您的需求:
public static Set<Method> findOverridingMethods(Object o) {
Set<Method> overridingMethods = new HashSet<Method>();
Class<?> clazz = o.getClass();
for (Method method : clazz.getDeclaredMethods()) {
Class<?> current = clazz.getSuperclass();
while (current != null) {
try {
current.getDeclaredMethod(method.getName(), method.getParameterTypes());
overridingMethods.add(method);
} catch (NoSuchMethodException ignore) {
}
current = current.getSuperclass();
}
}
return overridingMethods;
}
我认为您必须使用通过获得的Method
对象
getClass().getDeclaredMethod("hashCode").getDeclaringClass()