假设我正在尝试使用Method m = plugin.getClass().getDeclaredMethod("getFile");
从一个类中获取一个方法。
但是该plugin
类正在扩展另一个类,即具有getFile
方法的那个类。我不太确定这是否会让它抛出NoSuchMethodException
异常。
我知道plugin
正在扩展的类有getFile方法。抱歉,如果我听起来很困惑,有点累。
发布于 2013-07-31 01:40:22
听起来你只需要使用getMethod
而不是getDeclaredMethod
。getDeclaredMethod
的全部意义在于,它只查找在调用它的类中声明的方法:
返回一个Method对象,该对象反映这个class对象所表示的类或接口的指定声明方法。
而getMethod
具有:
在
C中搜索任何匹配的方法。如果没有找到匹配的方法,则在C的超类上递归调用步骤1的算法。
不过,这只能找到公共方法。如果您想要的方法不是公共的,您应该自己递归类层次结构,在层次结构中的每个类上使用getDeclaredMethod
或getDeclaredMethods
:
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();
}
https://stackoverflow.com/questions/17953724
复制相似问题