Reputation: 13
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.
Upvotes: 0
Views: 74
Reputation: 124225
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.
Upvotes: 1