簡體   English   中英

公用CLI CLI getValue()和getOptionValue()

[英]Commons CLI getValue() and getOptionValue()

我對這兩種方法有些疑惑。 當我使用getOptionValue(optionName) ,確實得到了我在命令行中輸入的參數,但是當我使用optionName.getValue()得到了null。

getValue()

返回此Option的指定值;如果沒有值,則返回null。

getOptionValue(String)

檢索此選項的第一個參數(如果有)。

如您所見, getOptionValue(String)顯式地表示參數,而另一個僅表示值,但它們的方法名中都帶有“值”。 由於沒有setValue(String)方法或類似的方法,我只是假設它與參數相同。

public static void main(final String[] args ) {
    CommandLine cmd = null;
    Option program = Option.builder("p")
             .hasArg()
             .required(true)
             .longOpt("program")
             .build();

    Options options = new Options();
    options.addOption( program );

    CommandLineParser parser = new DefaultParser();
    try {
        cmd = parser.parse( options, args );
    }
    catch( ParseException exp ) {
        System.err.println( "Parsing failed.  Reason: " + exp.getMessage() );
    }

    String[] list;
    list = cmd.getArgs();

    int argsN = program.getArgs();
    String optionValue = cmd.getOptionValue("p");
    String value = program.getValue();

    System.out.println(argsN);
    System.out.println(optionValue);
    System.out.println(value);

}

輸出為:

1個

[arg]

空值

我不知道為什么,但是目前看來這是故意的。 在第601行的handleOption()方法中的DefaultParser類中,代碼執行以下操作:

option = (Option) option.clone();

它專門切斷了傳入的選項和內部選項對象之間的聯系,似乎代碼不想更改以任何方式提供的對象。

因此,檢索值的唯一方法是通過CommandLine類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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