2014-07-09 60 views
0

好的,所以我有一種命令管理器用於我的一個程序。 即使世界一個名爲命令抽象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; 
    } 
} 
每個繼承這個類的

然後,我只是讓一些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."); 
     } 
    } 
} 

截至目前,該系統工作完全正常。但它有一個缺陷,對於我或其他編輯添加的每個命令,我們必須手動將它添加到列表中,這似乎很乏味,並且可能導致在我們同步文件時出現問題。所以我想知道,有什麼辦法可以將每個命令添加到列表中,而無需手動將它放在那裏?也許註釋我的方法,或者只是將它添加到列表中?我看到了一些關於反思的內容,但我不認爲這正是我想要的,儘管我不確定。 Iv從來沒有使用過,也沒有做過註釋,所以我不知道天氣與否,這是合理的。

回答

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; 
+0

好吧,所以我嘗試添加它,它究竟如何進入列表? commandlist.add(outerClazz);?不知道。 –

+0

我的歉意。我認爲你有互聯網接入和學習的願望。你可能想要谷歌你可以用一個Class對象做什麼。 – TedTrippin

+0

http://gyazo.com/a7512049cbc930a482a9edc34e1349f6仍然無法正確理解。我不擅長類型。 –

相關問題