args4j
args4j copied to clipboard
boolean option cannot have value
If I use the below code, I cannot pass "-v true" from command line since "true" will be parsed as an option but not a value for an option. This is largely due to the implementation of BooleanOptionHandler and NamedOptionDef. However, String option doesn't have this problem. Is this a bug or something by design? Cannot we make the two types consistent?
@Option(name = "-v", usage = "enable/disable validation mode")
private boolean validation = false;
As to my understanding the idea behind boolean switch is that, if it is specified amonst the arguments, then it is set to true. Eg.
program -dosomething something -skipimport
in the above example, there's no point for me to write -skipimport true
as it is already clear from the fact that I specified the parameter, that
it is true (as it is false by default).
Whereas there may be cases, when you want user to explicitly specify
behaviour of the program with the boolean key. For example you're importing
data to database from text file and it is important to specify whether
retries should be performed on error or not. In this case you may want to
have an explicit parameter: -retryonfail
myimport -someparam someparam -retryonfail true
But to implement the above you need to have a string parameter which with the required flag.
@Option(name="-retryonfail", usage="specify true or false of whether you
want to retry database insertion if the first attempt fails.",
required=true)
private String retryOnFail;
And then you check whether retryOnFail
equals "true"
or `"false"``.
So the bottom line is that, you can accomplish many things with the combination of boolan or string parameters.
Thanks dimkir for the quick response. Yes I can workaround that issue by using String and parse it to boolean in the code. So in args4j, we can only use boolean variable as a switch but not a key-value pair. I just expect consistent behaviors among all types (boolean, String, int, etc.). Anyway, thanks again.
Or for the lazy ExplicitBooleanOptionHandler
is also a way to go.
Simply add handler = ExplicitBooleanOptionHandler.class
to your @Option
annotation.