使用.getDeclaredMethod从扩展另一个类的类中获取方法

所以我想说我正在尝试使用Method m = plugin.getClass().getDeclaredMethod("getFile");从类中获取一个方法Method m = plugin.getClass().getDeclaredMethod("getFile");

但是该plugin类正在扩展另一个类,即使用getFile方法的类。 我不太确定是否会导致它抛出NoSuchMethodExceptionexception。

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

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

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

getMethod有:

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

那只会找到公共方法。 如果您所使用的方法不是公共的,则应自行递归类层次结构,使用层次结构中每个类的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(); }