【问题标题】:given an object how to know the overridden inherited methods [duplicate]给定一个对象如何知道被覆盖的继承方法[重复]
【发布时间】:2013-12-09 14:16:16
【问题描述】:

给定以下代码:

class A{
    int i;
        int hashcode(){
            . . .
        }
}

准确地说,给定A 的对象a,怎么能说继承自Object 类的hashcode() 在A 类中被覆盖。

a.getClass().getDeclaringClass() 正在返回 Objectclass。我希望它输出A。

【问题讨论】:

  • @sᴜʀᴇsʜᴀᴛᴛᴀ 请注意,我们不是在寻找覆盖的方法,而是寻找覆盖的方法。两者的解决方案不同。

标签: java reflection


【解决方案1】:

这应该适合您的需求:

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;
}

【讨论】:

    【解决方案2】:

    我认为你必须使用通过使用获得的Method对象

    getClass().getDeclaredMethod("hashCode").getDeclaringClass()
    

    【讨论】:

    • 它是如何工作的?你有什么可行的例子吗?
    • 这个是实际上是一个工作示例。
    猜你喜欢
    • 2019-04-27
    • 2015-09-19
    • 2012-05-23
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2012-07-28
    相关资源
    最近更新 更多