【问题标题】:Using .getDeclaredMethod to get a method from a class extending another使用 .getDeclaredMethod 从扩展另一个类的类中获取方法
【发布时间】:2013-07-30 17:38:44
【问题描述】:

假设我正在尝试使用Method m = plugin.getClass().getDeclaredMethod("getFile"); 从类中获取方法。

但是plugin 类正在扩展另一个类,即具有getFile 方法的类。我不太确定这是否会引发NoSuchMethodException 异常。

我知道plugin 扩展的类有getFile 方法。 对不起,如果我听起来很混乱,有点累。

【问题讨论】:

    标签: java reflection


    【解决方案1】:

    听起来您只需要使用getMethod 而不是getDeclaredMethodgetDeclaredMethod 的全部意义在于它找到在您调用它的类中声明的方法:

    返回一个 Method 对象,该对象反映此 Class 对象表示的类或接口的指定声明方法。

    getMethod 有:

    在 C 中搜索任何匹配的方法。如果没有找到匹配的方法,则在 C 的超类上递归调用步骤 1 的算法。

    这只会找到 public 方法。如果您使用的方法不是公开的,您应该自己递归类层次结构,在层次结构中的每个类上使用getDeclaredMethodgetDeclaredMethods

    Class<?> clazz = plugin.getClass();
    while (clazz != null) {
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            // Test any other things about it beyond the name...
            if (method.getName().equals("getFile") && ...) {
                return method;
            }
        }
        clazz = clazz.getSuperclass();
    }
    

    【讨论】:

    • 如果有帮助,我使用它的原因是因为该方法首先是私有的。然后你编辑。好的,我会尝试编辑。
    • @Ultimate:是的,这很重要。如果您一开始就提到这一点,那会有所帮助。
    • 嗯,这是很久以前的事了。很抱歉不接受这个!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2013-07-18
    • 2020-09-03
    • 2020-10-05
    • 1970-01-01
    • 2012-06-05
    相关资源
    最近更新 更多