![](/img/trans.png)
[英]How to use Java reflection to check if ParameterizedType argument extends a specific class
[英]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.