2013-02-03 52 views
3

我想以下工作:如何使用註釋自動分析我的命令行參數?

public class A { 
    @command_line_arg{"argname1"} 
    static boolean x; 

    @command_line_arg{"argname2"} 
    static List<String> y; 

    void main(String[] args) { 
     /* perhaps a call such as parseArgs(); here */ 
     System.out.println("got argname1 = " + x); 
     System.out.println("got argname2 = " + y); 
    } 
} 

我需要什麼庫使用?

(有點相關this。)

+1

也許使用jcommander? – fge

+0

好的,你在這裏;) – fge

回答

1

(基於@ FGE的answer

人們可以使用JCommander與靜:

public class A { 

    @Parameter(names = "-argname1") 
    static boolean x; 
    @Parameter(names = "-argname2", variableArity = true) 
    static List<String> y; 

    @Parameter 
    public static List<String> remainingParameters; 

    void main(String[] args) { 
     new JCommander(A.class.newInstance(), args); 
     System.out.println("got argname1 = " + x); 
     System.out.println("got argname2 = " + y); 
    } 
} 
1

你可以嘗試klab-commons-cli,它增加了註釋到Apache的commons-CLI;沒有發行jar,你只需使用源代碼。另一種不利用commons-cli,但提供分發庫的替代方法是args4j

+0

下載部分似乎是空的。我必須使用源代碼嗎? – einpoklum

+0

我已經編輯了我的答案,如果你需要一個jar有一個替代方案,它不會影響commons-cli,但是它和另一個一樣有效。 – remigio

+0

第一個的優點和缺點是什麼? – einpoklum

1

JCommander可能對您有些用處。它使用註釋來描述所有命令行參數併爲您生成選項/幫助文本。

報價在網站上找到的例子:

public class JCommanderExample { 
    @Parameter 
    private List<String> parameters = new ArrayList<String>(); 

    @Parameter(names = { "-log", "-verbose" }, description = "Level of verbosity") 
    private Integer verbose = 1; 

    @Parameter(names = "-groups", description = "Comma-separated list of group names to be run") 
    private String groups; 

    @Parameter(names = "-debug", description = "Debug mode") 
    private boolean debug = false; 
} 
+0

而且這個工作是否還會使用靜態變量?我只需要在我的應用類中運行主要方法... – einpoklum

+0

不是我所知道的......但是您可以在main()方法中執行'new Main()'並運行它。在運行時你只會有一個實例,所以這沒什麼大不了的。 – fge