[英]How do I find all Java objects (not classes) with a particular annotation?
[英]How do I make an annotation, that adds all classes of that type to a list
好的,所以我为我的一个程序提供了一种命令管理器。 有一个称为Command的抽象baceclass,它非常简单
public abstract class Command {
protected String commandheader;
protected int requiredlevel;
protected Random rand;
public Command(RANK rank,String command)
{
commandheader = command;
requiredlevel = rank.level;
}
}
然后,在每个继承此类的类中,我都说了一些神奇的东西。
public class MyCommand extends Command {
public MyCommand()
{
super(RANK.PLAYER,"blablabla");
}
}
然后,我还有一个命令帮助程序类,该类将这些命令中的每一个都保存在列表中,这样我可以轻松查找该命令在传递时是否有效,以及获得所有可用命令的简短信息。
public class CommandHelper {
public enum RANK{
PLAYER(0);
public int level;
private RANK(int i)
{
level = i;
}
}
static List<Command> commandlist;
private static void initTheCommands()
{
//Add the commands to the list here.
commandlist.add(new MyCommand());
}
//Called by my main class
public static void Init()
{
if(commandlist == null)
{
//Were safe to initalise the stuff brah.
commandlist = new ArrayList<Command>();
initTheCommands();
for(Command cmd : commandlist)
{
System.out.println("Loaded command: " + cmd.commandheader);
}
System.out.println("[INFO] Initalised the command helper");
}
else
{
System.out.println("[INFO] Command list is already populated.");
}
}
}
截至目前,该系统完全可以正常工作。 但这有一个缺陷,对于我或其他编辑者添加的每个命令,我们都必须手动将其添加到列表中,这似乎很繁琐,并且在我们同步文件时可能会导致问题。 所以我想知道,有什么方法可以将每个命令添加到列表中而不必手动将其添加到列表中? 也许注释我的方法,或者只是将其添加到列表中? 我看到了一些有关反射的内容,但我不确定我到底想要的是什么,尽管我不确定。 iv以前从未使用过或未做过注释,因此不确定天气是否合理。
如果那是您真正想要做的,则可以执行以下操作...
声明您的注释
@Target (ElementType.TYPE)
@Retention (RetentionPolicy.RUNTIME)
public @interface CommandAnnotation {
}
注释您的命令
@CommandAnnotation
public class MyCommand {
然后检查他们像这样
...
import org.reflections.Reflections;
...
public void loadCommands() {
Reflections reflections = new Reflections("com.my.package");
Set<Class<?>> allClasses = reflections.getSubTypesOf(Command.class);
for (Class<?> outerClazz : allClasses) {
CommandAnnotation annotation = outerClazz.getAnnotation(CommandAnnotation.class);
if (annotation == null)
continue;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.