Java Apache CLI OptionBuilder not working as Builder pattern

一个人想着一个人 提交于 2019-12-22 02:51:52

问题


I want to do something like

public static final Option job1 =
    OptionBuilder.hasArg(false)
        .isRequired(false)
        .withDescription("description of job1")
        .create(JOB1);

as mentioned How to specify multiple options using apache commons cli?

I am using maven dependency as

<dependency>
    <groupId>commons-cli</groupId>
    <artifactId>commons-cli</artifactId>
    <version>1.1</version>
</dependency>

as mentioned here - http://mvnrepository.com/artifact/commons-cli/commons-cli/1.1

But I am not able to, compiler complains

static member org.apache.commons.cli.OptionsBuilder.create() accessed via instance reference

, I even tried with <version>1.2</version>, but no luck, am I missing something?


回答1:


The problem is that every method in OptionBuilder is static, operating on static fields and returning a single static instance. Hence you don't require an instance of OptionBuilder to execute the methods. This doesn't marry well with the natural desire to chain the calls together, as you've done.

There is no solution other than to either calm the compiler down (perhaps disabling warnings in your IDE?) or adjust your code as follows (untested):

public static final Option job1;

static {
    OptionBuilder.hasArg(false);
    OptionBuilder.isRequired(false)
    OptionBuilder.withDescription("description of job1")
    job1 = OptionBuilder.create(JOB1);
}

It would be better if the OptionBuilder class was rewritten with a public no-argument constructor and only instance methods, thus behaving like every other builder out there. There is an existing bug in the commons-cli issue tracker highlighting this: https://issues.apache.org/jira/browse/CLI-224

Update: my patch has been submitted to trunk, so a new "proper" builder will be available in the next release of commons-cli (v1.3). See Javadocs here.



来源:https://stackoverflow.com/questions/12466955/java-apache-cli-optionbuilder-not-working-as-builder-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!