[英]Using .getDeclaredMethod to get a method from a class extending another
So lets say I am trying to get a method from a class using Method m = plugin.getClass().getDeclaredMethod("getFile");
所以我想说我正在尝试使用
Method m = plugin.getClass().getDeclaredMethod("getFile");
从类中获取一个方法Method m = plugin.getClass().getDeclaredMethod("getFile");
. 。
But that plugin
class is extending another class, which is the one with the getFile
method. 但是该
plugin
类正在扩展另一个类,即使用getFile
方法的类。 I am not quite sure if that would make it throw the NoSuchMethodException
exception or not. 我不太确定是否会导致它抛出
NoSuchMethodException
异常。
I know the class that the plugin
is extending has the getFile method. 我知道
plugin
扩展的类有getFile方法。 Sorry if I sound confusing, a bit tired. 对不起,如果我听起来很混乱,有点累。
It sounds like you just need to use getMethod
instead of getDeclaredMethod
. 听起来你只需要使用
getMethod
而不是getDeclaredMethod
。 The whole point of getDeclaredMethod
is that it only finds methods declared in the class you're calling it on: getDeclaredMethod
的全部意义在于它只查找在您调用它的类中声明的方法:
Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
返回一个Method对象,该对象反映此Class对象所表示的类或接口的指定声明方法。
Whereas getMethod
has: 而
getMethod
有:
C is searched for any matching methods.
搜索C以寻找任何匹配方法。 If no matching method is found, the algorithm of step 1 is invoked recursively on the superclass of C.
如果没有找到匹配方法,则在C的超类上递归调用步骤1的算法。
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: 如果您所使用的方法不是公共的,则应该在层次结构中的每个类上使用
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.