简体   繁体   中英

Reflection and class that extends

I have a problem with using Reflection in Java. This is my SubCommandExecutor class, a class that handles all the commands sent:

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. 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.

I even create a TestCommand class that extends SubCommandExecutor:

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.

There is any way to fix this problem? Thank you very much.

Methods in TestCommand class are private but in

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

getMethods() can return only public ones (including inherited ones).

If you want to use methods declared in TestCommand use getDeclaredMethods() .
Other option is to change your annotated methods to public .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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