使用.getDeclaredMethod从扩展另一个类的类中获取方法 [英] Using .getDeclaredMethod to get a method from a class extending another

查看:397
本文介绍了使用.getDeclaredMethod从扩展另一个类的类中获取方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想说我试图从类中使用方法获取方法m = plugin.getClass()。getDeclaredMethod(getFile);

So lets say I am trying to get a method from a class using Method m = plugin.getClass().getDeclaredMethod("getFile");.

但是插件类正在扩展另一个类,即具有 getFile的类方法。我不太确定是否会使它抛出 NoSuchMethodException 异常。

But that plugin class is extending another class, which is the one with the getFile method. I am not quite sure if that would make it throw the NoSuchMethodException exception or not.

我知道插件正在扩展的类具有getFile方法。
很抱歉,如果我听起来有点混乱,有点累。

I know the class that the plugin is extending has the getFile method. Sorry if I sound confusing, a bit tired.

推荐答案

听起来你只需要使用 getMethod 而不是 getDeclaredMethod getDeclaredMethod 找到您正在调用的类中声明的方法它打开:

It sounds like you just need to use getMethod instead of getDeclaredMethod. The whole point of getDeclaredMethod is that it only finds methods declared in the class you're calling it on:


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

Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.

getMethod


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

C is searched for any matching methods. If no matching method is found, the algorithm of step 1 is invoked recursively on the superclass of C.

这只会找到公共方法。如果您所使用的方法不公开,则应使用 getDeclaredMethod getDeclaredMethods 在层次结构中的每个类上:

That will only find public methods though. If the method you're after isn't public, you should recurse up the class hierarchy yourself, using getDeclaredMethod or getDeclaredMethods on each class in the hierarchy:

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

这篇关于使用.getDeclaredMethod从扩展另一个类的类中获取方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆