给定一个对象如何知道被重写的继承方法



给定以下代码:

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()

最新更新