2011-04-07 18 views
34

如何爲CLI選項指定類型 - 例如intInteger? (後來,我怎樣才能得到解析的值與一個單一的函數調用?)Apache Commons CLI - 選項類型和默認值

我怎樣才能給一個CLI選項的默認值?這樣CommandLine.getOptionValue()或上面提到的函數調用返回該值,除非在命令行中指定了一個值?

回答

43

編輯:默認值現在支持。請參閱下面的回答https://stackoverflow.com/a/14309108/1082541

正如布倫特沃登已經提到的,不支持默認值。

我也有使用Option.setType的問題。對類型爲Integer.class的選項調用getParsedOptionValue時,我總是得到空指針異常。由於文檔不是很有幫助,我查看了源代碼。在TypeHandler

展望和PatternOptionBuilder類,你可以看到Number.class必須用於intInteger

這裏是一個簡單的例子:

CommandLineParser cmdLineParser = new PosixParser(); 

Options options = new Options(); 
options.addOption(OptionBuilder.withLongOpt("integer-option") 
         .withDescription("description") 
         .withType(Number.class) 
         .hasArg() 
         .withArgName("argname") 
         .create()); 

try { 
    CommandLine cmdLine = cmdLineParser.parse(options, args); 

    int value = 0; // initialize to some meaningful default value 
    if (cmdLine.hasOption("integer-option")) { 
     value = ((Number)cmdLine.getParsedOptionValue("integer-option")).intValue(); 
    } 

    System.out.println(value); 
} catch (ParseException e) { 
    e.printStackTrace(); 
} 

請記住,如果提供了一些不適合的intvalue可能溢出。

+8

謝謝你的例子,這是我需要的。但是,我決定反對CLI:這是太多的工作。也許這只是我,但是當你必須處理這樣的常見情況時,我發現它是自我挫敗的。如果有足夠的設置代碼,我應該只能說'int foo = getOption(「foo」)',並且如果出現任何錯誤,它將默認爲42。 – aib 2011-05-11 03:03:14

+1

是的,你是對的。我也認爲圖書館應該處理這些東西。你可以推薦哪個選項解析庫? – 2011-05-11 08:20:55

+0

我是新來的Java世界。這是我嘗試的第一個,我也不知道其他人。也許你應該將此作爲一個問題發佈? – aib 2011-05-11 12:59:39

1

CLI不支持默認值。任何未設置的選項都會導致getOptionValue返回null

可以使用Option.setType方法指定選項類型,並提取解析選項的值作爲該類型使用CommandLine.getParsedOptionValue

+0

的可變我知道的setType()和getParsedOptionValue的存在(),但不知道如何使用它們。你能給我一個小例子嗎? – aib 2011-04-08 04:35:20

23

我不知道,如果不工作,或者最近添加但getOptionValue()重載版本接受默認(字符串)值

+0

這正是我2年前所需要的:) – aib 2013-01-14 02:53:59

+0

@aib:很高興幫助 - 當時是否存在? – 2013-01-14 11:38:30

+0

我想不是,否則我會看到它。 (或者至少有其他人在這裏) – aib 2013-01-14 13:33:06

1

的OptionBuilder在版本棄用1.3 & 1.4和Option.Builder沒有按」 t似乎具有設置類型的直接功能。 Option類有一個函數叫做setType。您可以使用功能CommandLine.getParsedOptionValue檢索轉換後的值。 不知道爲什麼它不再是構建器的一部分。它要求現在有些這樣的代碼:

options = new Options(); 

    Option minOpt = Option.builder("min").hasArg().build(); 
    minOpt.setType(Number.class); 
    options.addOption(minOpt); 

和閱讀它:

String testInput = "-min 14"; 
    String[] splitInput = testInput.split("\\s+"); 

    CommandLine cmd = CLparser.parse(options, splitInput); 
    System.out.println(cmd.getParsedOptionValue("min")); 

這將使類型Long