[英]Reflection and class that extends
I have a problem with using Reflection in Java. 我在Java中使用Reflection时遇到问题。 This is my SubCommandExecutor class, a class that handles all the commands sent: 这是我的SubCommandExecutor类,该类处理所有发送的命令:
public class SubCommandExecutor implements CommandExecutor{
@Override
public final boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length > 0){
Method[] meth = this.getClass().getMethods();
for (int i = 0; i < meth.length; i++){
SubCommand sub = meth[i].getAnnotation(SubCommand.class);
if (sub != null){
// some reflaction staff
}
}
} else {
// ...
}
}
}
Everytime that a command is executed, the onCommand method is called. 每次执行命令时,都会调用onCommand方法。 In the onCommand method I would like to loop through all the class methods to find if there is any method with the SubCommand annotation. 在onCommand方法中,我想遍历所有类方法以查找是否有带有SubCommand批注的方法。
I even create a TestCommand class that extends SubCommandExecutor: 我什至创建一个扩展SubCommandExecutor的TestCommand类:
public class TestCommand extends SubCommandExecutor {
@SubCommand(command="a")
private boolean cmdA(CommandSender sender){
// ...
}
@SubCommand(command="b")
private boolean cmdB(CommandSender sender, String[] args){
// ...
}
@SubCommand(command="c")
private boolean cmdC(CommandSender sender, String[] args){
// ...
}
}
The problem is that where I call the onCommand method of the TestCommand class (inherited by the SubCommandExecutor), it loops only through the methods of the SubCommandExecutor and not throught the methods of TextCommand. 问题是,在我调用TestCommand类的onCommand方法(由SubCommandExecutor继承)的地方,它仅通过SubCommandExecutor的方法循环,而没有通过TextCommand的方法循环。
There is any way to fix this problem? 有什么办法可以解决这个问题? Thank you very much. 非常感谢你。
Methods in TestCommand
class are private
but in TestCommand
类中的方法是private
但在
Method[] meth = this.getClass().getMethods();
getMethods()
can return only public
ones (including inherited ones). getMethods()
只能返回public
的(包括继承的)。
If you want to use methods declared in TestCommand
use getDeclaredMethods()
. 如果要使用在TestCommand
声明的方法, TestCommand
使用getDeclaredMethods()
。
Other option is to change your annotated methods to public . 另一种选择是将带注释的方法更改为public 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.