【问题标题】:How do I make an annotation, that adds all classes of that type to a list如何进行注释,将该类型的所有类添加到列表中
【发布时间】:2014-07-09 23:25:02
【问题描述】:

好的,所以我有一个用于我的一个程序的命令管理器。 有一个叫做 Command 的抽象类,非常简单

public abstract class Command {

    protected String commandheader;
    protected int requiredlevel;
    protected Random rand;
    public Command(RANK rank,String command)
    {
        commandheader = command;
        requiredlevel = rank.level;
    }
}

然后在每个继承它的类中,我只是这么一些 oop 魔术。

public class MyCommand extends Command {

    public MyCommand()
    {
        super(RANK.PLAYER,"blablabla");
    }
}

然后我还有一个命令助手类,它将这些命令中的每一个保存在一个列表中,这样当我传入命令时,我可以很容易地找到命令是否有效,以及获取所有可用命令的 lsit。

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.");
        }
    }
}

截至目前,该系统运行良好。但它有一个缺陷,对于我或其他编辑器添加的每个命令,我们都必须手动将其添加到列表中,这似乎很乏味,并且在我们同步文件时可能会导致问题。所以我想知道,有什么方法可以将每个命令添加到列表中,而无需手动将其放在那里?也许注释我的方法,或者只是将它添加到列表中?我看到了一些关于反射的东西,但我不认为这正是我想要的,尽管我不确定。我以前从未使用过或做过注释,所以我不确定天气是否合理。

【问题讨论】:

    标签: java list class annotations


    【解决方案1】:

    如果那是你真正想做的事情,你可以做这样的事情......

    声明你的注释

    @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;
    

    【讨论】:

    • 好的,所以我尝试添加它,它究竟是如何进入列表的? commandlist.add(outerClazz);?不知道。
    • 我很抱歉。我假设你有互联网接入和学习的愿望。你可能想用谷歌搜索你可以用 Class 对象做什么。
    • gyazo.com/a7512049cbc930a482a9edc34e1349f6 仍然无法正确处理。我不擅长 > 类型。
    猜你喜欢
    • 2020-06-17
    • 1970-01-01
    • 2021-12-27
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 2011-09-24
    • 2020-01-22
    相关资源
    最近更新 更多