Closed hq6 closed 2 months ago
For options that have an Optional<T>
type, picocli will convert null
values to Optional.empty()
.
On the command line, users can only pass in Strings (resulting in the String[] args
array that is passed to the main
method).
The type converters are responsible for converting String values to Java objects.
Picocli provides built-in type converters for many common types, including for int
and java.lang.Integer
. However, the built-in type converter for integer values will never produce a null
value, so you need to install a custom type converter that produces the null
value for some String argument(s).
Then, passing these special values on the command line will result in Optional.empty()
values being assigned to the option.
Something like this:
public static main(String... args) {
CommandLine cmd = new CommandLine(new MWE())
.registerConverter(Integer.class, s -> new MyNullableIntConverter())
.registerConverter(Integer.TYPE, s -> new MyNullableIntConverter());
cmd.execute(args);
}
static class MyNullableIntConverter implements ITypeConverter<Integer> {
public Integer convert(String value) throws Exception {
// make "null" and "Optional.empty" special values that will result in Optional.empty()
if ("null".equals(value)) { return null; }
else if ("Optional.empty".equals(value)) { return null; }
// normal processing for non-special values
return Integer.valueOf(value);
}
}
I will close this ticket, feel free to ask more questions or re-open if necessary.
Consider the following MWE:
If I invoke this as
java MWE -d 6
, I get the following output, as expected:However, if I try either of the following, I get an exception:
Is there some magic incantation I can use to pass Optional.empty() on the command line for an Optional argument?