繁体   English   中英

反思和延伸的阶级

[英]Reflection and class that extends

我在Java中使用Reflection时遇到问题。 这是我的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 {
             // ...
        }
    }
}

每次执行命令时,都会调用onCommand方法。 在onCommand方法中,我想遍历所有类方法以查找是否有带有SubCommand批注的方法。

我什至创建一个扩展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){
        // ...
    }

}

问题是,在我调用TestCommand类的onCommand方法(由SubCommandExecutor继承)的地方,它仅通过SubCommandExecutor的方法循环,​​而没有通过TextCommand的方法循环。

有什么办法可以解决这个问题? 非常感谢你。

TestCommand类中的方法是private但在

Method[] meth = this.getClass().getMethods();

getMethods()只能返回public的(包括继承的)。

如果要使用在TestCommand声明的方法, TestCommand使用getDeclaredMethods()
另一种选择是将带注释的方法更改为public

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM