Picocli:为具有地图类型的选项指定默认值

Picocli: Specify default value for an option which has a type of Map

我有这样的选择

    @CommandLine.Option(names = "-D", description = "Define a symbol.")
    /* A list of defines provided by the user. */
    Map<String, String> defines = new LinkedHashMap<String, String>();

当我执行以下操作时,这确实有效:

-Dkey=value

然而当我这样做时

-Dkey

它不起作用。有没有办法为没有关联值的键添加默认值?

更新:从 picocli 4.6 开始,这可以通过在选项或位置参数中指定 mapFallbackValue 来完成。

@Option(names = {"-P", "--properties"}, mapFallbackValue = Option.NULL_VALUE)
Map<String, Optional<Integer>> properties;

@Parameters(mapFallbackValue= "INFO", description= "... ${MAP-FALLBACK-VALUE} ...")
Map<Class<?>, LogLevel> logLevels;

值类型可能包含在 java.util.Optional 中。 (如果不是,并且后备值为 Option.NULL_VALUE,picocli 会将值 null 放入指定键的映射中。)


(原回答如下):

这可以通过 custom parameterConsumer 来完成。例如:

/* A list of defines provided by the user. */
@Option(names = "-D", parameterConsumer = MyMapParameterConsumer.class,
  description = "Define a symbol.")
Map<String, String> defines = new LinkedHashMap<String, String>();

... 其中 MyMapParameterConsumer 看起来像这样:


class MyMapParameterConsumer implements IParameterConsumer {
    @Override
    public void consumeParameters(
            Stack<String> args, 
            ArgSpec argSpec, 
            CommandSpec commandSpec) {

        if (args.isEmpty()) {
            throw new ParameterException(commandSpec.commandLine(), 
                    "Missing required parameter");
        }
        String parameter = args.pop();
        String[] keyValue = parameter.split("=", 1);
        String key = keyValue[0];
        String value = keyValue.length > 1 
                ? keyValue[1]
                : "MY_DEFAULT";
        Map<String, String> map = argSpec.getValue();
        map.put(key, value);
    }
}