我尝试测试Annotation如何工作,但没有按计划进行。当我尝试运行应用程序时,一切正常,除非ReadCommandAnnotation类无法从方法或类中检索Annotation中的值。 现在,我并不完全知道如何真正做到这一点,我愿意提供帮助,并提示如何改进这一点。我有一个计划,为什么我要使用它,但现在我被困在这一点。
不起作用的示例:命令,描述,别名,等级,可用
TL; DR,我想从每个方法/类的注释中检索值。我不明白自己该怎么做..
在此课程中注册所有注释值。
public class ReadCommandAnnotation {
private final Class<?> clazz;
private String command;
private String[] description;
private boolean useable;
private String[] aliases;
private int rank;
public ReadCommandAnnotation(final Class<?> clazz) {
this.clazz = clazz.getClass();
this.register();
}
public void register() {
Method[] methods = clazz.getClass().getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(CommandAnnotation.class)) {
CommandAnnotation commandAnnotation = method.getAnnotation(CommandAnnotation.class);
this.command = commandAnnotation.command();
this.description = commandAnnotation.description();
this.useable = commandAnnotation.use();
this.rank = commandAnnotation.rankRequired();
this.alises = commandAnnotation.aliases();
}
}
}
注释界面,我认为这里的一切都应该正常......?
@Retention(RetentionPolicy.RUNTIME)
public @interface CommandAnnotation {
String DEFAULT_MESSAGE = "N/A";
int DEFAULT_INTEGER = 1;
String command() default DEFAULT_MESSAGE;
String[] aliases() default { DEFAULT_MESSAGE };
String[] description() default { DEFAULT_MESSAGE };
int rankRequired() default DEFAULT_INTEGER;
boolean use() default true;
“主要”课程。 (onEnable)方法是我运行一切的地方。 (SPONGE API已实施)
@Override
public void onEnable() {
testCommandAnnotation();
}
@Override
public void onDisable() {
}
@CommandAnnotation(command = "testCommand" , aliases = {"fancyCommand", "coolCommand"} , description = {"A test command execution.."} , rankRequired = 30, use = true)
public void testCommandAnnotation() {
ReadCommandAnnotation readAnnotation = new ReadCommandAnnotation(this.getClass());
readAnnotation.register();
System.out.println("Command: " + readAnnotation.getCommand());
}
不知怎的,当我执行这个时,我起床的是控制台中的“N / A”。