簡體   English   中英

如何做注釋,將所有該類型的類添加到列表中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM