CommandLine.Option (picocli 4.6.3 API)

picocli

## Annotation Type CommandLine.Option

-     @Retention(value=RUNTIME)
       @Target(value={FIELD,METHOD,PARAMETER})
      public static @interface CommandLine.Option

  Annotate fields in your class with `@Option` and picocli will initialize these fields when matching arguments are specified on the command line. In the case of command methods (annotated with `@Command`), command options can be defined by annotating method parameters with `@Option`.

  Command class example:

       import static picocli.CommandLine.*;

       public class MyClass {
           @Parameters(description = "Any number of input files")
           private List<File> files = new ArrayList<File>();

           @Option(names = { "-o", "--out" }, description = "Output file (default: print to console)")
           private File outputFile;

           @Option(names = { "-v", "--verbose"}, description = "Verbose mode. Helpful for troubleshooting. Multiple -v options increase the verbosity.")
           private boolean[] verbose;

           @Option(names = { "-h", "--help", "-?", "-help"}, usageHelp = true, description = "Display this help and exit")
           private boolean help;
       }

  A field cannot be annotated with both `@Parameters` and `@Option` or a `ParameterException` is thrown.

- - ### Field Summary

    Fields
    Modifier and Type | Fields and Description
    --- | ---
    `static String` | `NULL_VALUE` Special value that can be used in some annotation attributes to designate `null`.

  - ### Required Element Summary

    Required Elements
    Modifier and Type | Required Element and Description
    --- | ---
    `String[]` | `names` One or more option names.

  - ### Optional Element Summary

    Optional Elements
    Modifier and Type | Optional Element and Description
    --- | ---
    `String` | `arity` Specifies the minimum number of required parameters and the maximum number of accepted parameters.
    `Class<? extends Iterable<String>>` | `completionCandidates` Use this attribute to specify an `Iterable<String>` class that generates completion candidates for this option.
    `Class<? extends CommandLine.ITypeConverter<?>>[]` | `converter` Optionally specify one or more `CommandLine.ITypeConverter` classes to use to convert the command line argument into a strongly typed value (or key-value pair for map fields).
    `String` | `defaultValue` Returns the default value of this option, before splitting and type conversion.
    `String[]` | `description` Description of this option, used when generating the usage documentation.
    `String` | `descriptionKey` ResourceBundle key for this option.
    `boolean` | `echo` Use this attribute to control whether user input for an interactive option is echoed to the console or not.
    `String` | `fallbackValue` For options with an optional parameter (for example, `arity = "0..1"`), this value is assigned to the annotated element if the option is specified on the command line without an option parameter.
    `boolean` | `help` This should rarely be used: the recommended attributes are `usageHelp` and `versionHelp`.
    `boolean` | `hidden` Set `hidden=true` if this option should not be included in the usage help message.
    `boolean` | `hideParamSyntax` Returns whether usage syntax decorations around the paramLabel should be suppressed.
    `boolean` | `interactive` Set `interactive=true` to make this option prompt the end user for a value (like a password).
    `String` | `mapFallbackValue` For options of type Map, setting the `mapFallbackValue` to any value allows end user to specify key-only parameters for this option.
    `boolean` | `negatable` (Only for boolean options): set this to automatically add a negative version for this boolean option.
    `int` | `order` When `@Command(sortOptions = false)` is specified, this attribute can be used to control the order in which options are listed in the usage help message.
    `Class<? extends CommandLine.IParameterConsumer>` | `parameterConsumer` Optionally specify a custom `IParameterConsumer` to temporarily suspend picocli's parsing logic and process one or more command line arguments in a custom manner.
    `String` | `paramLabel` Specify a `paramLabel` for the option parameter to be used in the usage help message.
    `Class<? extends CommandLine.IParameterPreprocessor>` | `preprocessor` Returns the preprocessor for this option.
    `String` | `prompt` Use this attribute to customize the text displayed to the end user for an interactive option when asking for user input.
    `boolean` | `required` Indicates whether this option is required.
    `CommandLine.ScopeType` | `scope` Determines on which command(s) this option exists: on this command only (the default), or whether this is a "global" option that is applied to this command and all subcommands, sub-subcommands, etc.
    `CommandLine.Help.Visibility` | `showDefaultValue` Use this attribute to control for a specific option whether its default value should be shown in the usage help message.
    `String` | `split` Specify a regular expression to use to split option parameter values before applying them to the field.
    `String` | `splitSynopsisLabel` Specify the string to display for the `split` regular expression in the usage help synopsis.
    `Class<?>[]` | `type` Optionally specify a `type` to control exactly what Class the option parameter should be converted to.
    `boolean` | `usageHelp` Set `usageHelp=true` for the `--help` option that triggers display of the usage help message.
    `boolean` | `versionHelp` Set `versionHelp=true` for the `--version` option that triggers display of the version information.

- - ### Field Detail

    - #### NULL_VALUE

          public static final String NULL_VALUE

      Special value that can be used in some annotation attributes to designate `null`.
      Since:
        4.6
      See Also:
        `defaultValue()`, `fallbackValue()`, `mapFallbackValue()`

  - ### Element Detail

    - #### names

          public abstract String[] names

      One or more option names. At least one option name is required.

      Different environments have different conventions for naming options, but usually options have a prefix that sets them apart from parameters. Picocli supports all of the below styles. The default separator is `'='`, but this can be configured.

      *nix

      In Unix and Linux, options have a short (single-character) name, a long name or both. Short options (POSIX style are single-character and are preceded by the `'-'` character, e.g., ``-v'`. GNU-style long (or mnemonic) options start with two dashes in a row, e.g., ``--file'`.

      Picocli supports the POSIX convention that short options can be grouped, with the last option optionally taking a parameter, which may be attached to the option name or separated by a space or a `'='` character. The below examples are all equivalent:

           -xvfFILE
           -xvf FILE
           -xvf=FILE
           -xv --file FILE
           -xv --file=FILE
           -x -v --file FILE
           -x -v --file=FILE

      DOS

      DOS options mostly have upper case single-character names and start with a single slash `'/'` character. Option parameters are separated by a `':'` character. Options cannot be grouped together but must be specified separately. For example:

           DIR /S /A:D /T:C

      PowerShell

      Windows PowerShell options generally are a word preceded by a single `'-'` character, e.g., ``-Help'`. Option parameters are separated by a space or by a `':'` character.

      Returns:
        one or more option names

  - - #### required

          public abstract boolean required

      Indicates whether this option is required. By default this is false.

      If an option is required, but a user invokes the program without specifying the required option, a `CommandLine.MissingParameterException` is thrown from the `CommandLine.parse(String...)` method.

      Required options that are part of a group are required within the group, not required within the command: the group's multiplicity determines whether the group itself is required or optional.

      Returns:
        whether this option is required
      Default:
        false

  - - #### help

          public abstract boolean help

      This should rarely be used: the recommended attributes are `usageHelp` and `versionHelp`.

      Only set `help=true` when this option should disable validation of the remaining arguments, and no error message should be generated for missing required options.

      This is useful for custom help options that are in addition to the standard help and version options. For example if your application has many hidden options or subcommands, and there is a custom help option like `--detailed-help` that prints the usage help message for these hidden options and subcommands.

      Note:

      Use the `usageHelp` for "normal" help options (like `-h` and `--help` on unix, `-?` and `-Help` on Windows) and use `versionHelp` for "normal" version help (`-V` and `--version` on unix, `-Version` on Windows): picocli has built-in logic so that options with `usageHelp=true` or `versionHelp=true` will automatically cause the requested help message to be printed in applications that use the `CommandLine.execute(String...)` method, without any code in the application.

      Note that there is no such automatic help printing for options with `help=true`; applications need to check whether the end user specified this option and take appropriate action in the business logic of the application.

      Returns:
        whether this option disables validation of the other arguments
      Default:
        false

  - - #### usageHelp

          public abstract boolean usageHelp

      Set `usageHelp=true` for the `--help` option that triggers display of the usage help message. The convenience methods `Commandline.call`, `Commandline.run`, and `Commandline.parseWithHandler(s)` will automatically print usage help when an option with `usageHelp=true` was specified on the command line.

      By default, all options and positional parameters are included in the usage help message except when explicitly marked hidden.

      If this option is specified on the command line, picocli will not validate the remaining arguments (so no "missing required option" errors) and the `CommandLine.isUsageHelpRequested()` method will return `true`.

      Alternatively, consider annotating your command with @Command(mixinStandardHelpOptions = true).

      Returns:
        whether this option allows the user to request usage help
      Since:
        0.9.8
      See Also:
        `hidden()`, `CommandLine.run(Runnable, String...)`, `CommandLine.call(Callable, String...)`, `CommandLine.parseWithHandler(IParseResultHandler2, String[])`, `CommandLine.printHelpIfRequested(List, PrintStream, PrintStream, Help.Ansi)`
      Default:
        false

  - - #### versionHelp

          public abstract boolean versionHelp

      Set `versionHelp=true` for the `--version` option that triggers display of the version information. The convenience methods `Commandline.call`, `Commandline.run`, and `Commandline.parseWithHandler(s)` will automatically print version information when an option with `versionHelp=true` was specified on the command line.

      The version information string is obtained from the command's version annotation or from the version provider.

      If this option is specified on the command line, picocli will not validate the remaining arguments (so no "missing required option" errors) and the `CommandLine.isUsageHelpRequested()` method will return `true`.

      Alternatively, consider annotating your command with @Command(mixinStandardHelpOptions = true).

      Returns:
        whether this option allows the user to request version information
      Since:
        0.9.8
      See Also:
        `hidden()`, `CommandLine.run(Runnable, String...)`, `CommandLine.call(Callable, String...)`, `CommandLine.parseWithHandler(IParseResultHandler2, String[])`, `CommandLine.printHelpIfRequested(List, PrintStream, PrintStream, Help.Ansi)`
      Default:
        false

  - - #### description

          public abstract String[] description

      Description of this option, used when generating the usage documentation. Each element of the array is rendered on a separate line.

      May contain embedded format specifiers like `%n` line separators. Literal percent `'%'` characters must be escaped with another `%`.

      The description may contain variables that are rendered when help is requested. The string `${DEFAULT-VALUE}` is replaced with the default value of the option. This is regardless of the command's `showDefaultValues` setting or the option's `showDefaultValue` setting. The string `${COMPLETION-CANDIDATES}` is replaced with the completion candidates generated by `completionCandidates()` in the description for this option. Also, embedded `%n` newline markers are converted to actual newlines.

      Returns:
        the description of this option
      See Also:
        Variable Interpolation section of the user manual
      Default:
        {}

  - - #### arity

          public abstract String arity

      Specifies the minimum number of required parameters and the maximum number of accepted parameters. If an option declares a positive arity, and the user specifies an insufficient number of parameters on the command line, a `CommandLine.MissingParameterException` is thrown by the `CommandLine.parse(String...)` method.

      In many cases picocli can deduce the number of required parameters from the field's type. By default, flags (boolean options) have arity "0..1", and single-valued type fields (String, int, Integer, double, Double, File, Date, etc) have arity one. Generally, fields with types that cannot hold multiple values can omit the `arity` attribute.

      Fields used to capture options with arity two or higher should have a type that can hold multiple values, like arrays or Collections. See `type()` for strongly-typed Collection fields.

      For example, if an option has 2 required parameters and any number of optional parameters, specify `@Option(names = "-example", arity = "2..*")`.

      A note on boolean options

      By default picocli allows boolean options (also called "flags" or "switches") to have an optional parameter, which must be either "true" or "false" (lowercase, other values are rejected). You can make a boolean option take a required parameter by annotating your field with `arity="1"`. For example:

          @Option(names = "-v", arity = "1") boolean verbose;

      Because this boolean field is defined with arity 1, the user must specify either `<program> -v false` or `<program> -v true` on the command line, or a `CommandLine.MissingParameterException` is thrown by the `CommandLine.parse(String...)` method.

      To remove the optional parameter, define the field with `arity = "0"`. For example:

          @Option(names="-v", arity="0") boolean verbose;

      This will reject any of the below:

           -v true
           -v false

      Returns:
        how many arguments this option requires
      Default:
        ""

  - - #### paramLabel

          public abstract String paramLabel

      Specify a `paramLabel` for the option parameter to be used in the usage help message. If omitted, picocli uses the field name in fish brackets (`'<'` and `'>'`) by default. Example:

          class Example {
               @Option(names = {"-o", "--output"}, paramLabel="FILE", description="path of the output file")
               private File out;
               @Option(names = {"-j", "--jobs"}, arity="0..1", description="Allow N jobs at once; infinite jobs with no arg.")
               private int maxJobs = -1;
           }

      By default, the above gives a usage help message like the following:

           Usage: <main class> [OPTIONS]
           -o, --output FILE       path of the output file
           -j, --jobs [<maxJobs>]  Allow N jobs at once; infinite jobs with no arg.

      Returns:
        name of the option parameter used in the usage help message
      Default:
        ""

  - - #### hideParamSyntax

          public abstract boolean hideParamSyntax

      Returns whether usage syntax decorations around the paramLabel should be suppressed. The default is `false`: by default, the paramLabel is surrounded with `'['` and `']'` characters if the value is optional and followed by ellipses ("...") when multiple values can be specified.
      Since:
        3.6.0
      Default:
        false

  - - #### type

          public abstract Class<?>[] type

      Optionally specify a `type` to control exactly what Class the option parameter should be converted to. This may be useful when the field type is an interface or an abstract class. For example, a field can be declared to have type `java.lang.Number`, and annotating `@Option(type=Short.class)` ensures that the option parameter value is converted to a `Short` before setting the field value.

      For array fields whose component type is an interface or abstract class, specify the concrete component type. For example, a field with type `Number[]` may be annotated with `@Option(type=Short.class)` to ensure that option parameter values are converted to `Short` before adding an element to the array.

      Picocli will use the `CommandLine.ITypeConverter` that is registered for the specified type to convert the raw String values before modifying the field value.

      Prior to 2.0, the `type` attribute was necessary for `Collection` and `Map` fields, but starting from 2.0 picocli will infer the component type from the generic type's type arguments. For example, for a field of type `Map<TimeUnit, Long>` picocli will know the option parameter should be split up in key=value pairs, where the key should be converted to a `java.util.concurrent.TimeUnit` enum value, and the value should be converted to a `Long`. No `@Option(type=...)` type attribute is required for this. For generic types with wildcards, picocli will take the specified upper or lower bound as the Class to convert to, unless the `@Option` annotation specifies an explicit `type` attribute.

      If the field type is a raw collection or a raw map, and you want it to contain other values than Strings, or if the generic type's type arguments are interfaces or abstract classes, you may specify a `type` attribute to control the Class that the option parameter should be converted to.

      Returns:
        the type(s) to convert the raw String values
      Default:
        {}

  - - #### converter

          public abstract Class<? extends CommandLine.ITypeConverter<?>>[] converter

      Optionally specify one or more `CommandLine.ITypeConverter` classes to use to convert the command line argument into a strongly typed value (or key-value pair for map fields). This is useful when a particular field should use a custom conversion that is different from the normal conversion for the field's type.

      For example, for a specific field you may want to use a converter that maps the constant names defined in `java.sql.Types` to the `int` value of these constants, but any other `int` fields should not be affected by this and should continue to use the standard int converter that parses numeric values.

      Returns:
        the type converter(s) to use to convert String values to strongly typed values for this field
      See Also:
        `CommandLine.registerConverter(Class, ITypeConverter)`
      Default:
        {}

  - - #### split

          public abstract String split

      Specify a regular expression to use to split option parameter values before applying them to the field. All elements resulting from the split are added to the array or Collection. Previously ignored for single-value fields, from picocli 4.0 a `split` regex can only be specified on multi-value options and positional parameters.
      Returns:
        a regular expression to split option parameter values or `""` if the value should not be split
      See Also:
        `String.split(String)`
      Default:
        ""

  - - #### splitSynopsisLabel

          public abstract String splitSynopsisLabel

      Specify the string to display for the `split` regular expression in the usage help synopsis.
      Since:
        4.3
      Default:
        ""

  - - #### hidden

          public abstract boolean hidden

      Set `hidden=true` if this option should not be included in the usage help message.
      Returns:
        whether this option should be excluded from the usage documentation
      Default:
        false

  - - #### defaultValue

          public abstract String defaultValue

      Returns the default value of this option, before splitting and type conversion.

      To get a `null` default value, omit specifying a default value or use the special value `NULL_VALUE` - for options of type `Optional<T>` that will result in the `Optional.empty()` value being assigned when the option is not specified on the command line.

      Returns:
        a String that (after type conversion) will be used as the value for this option if the option was not specified on the command line
      Since:
        3.2
      See Also:
        `fallbackValue()`
      Default:
        "__no_default_value__"

  - - #### showDefaultValue

          public abstract CommandLine.Help.Visibility showDefaultValue

      Use this attribute to control for a specific option whether its default value should be shown in the usage help message. If not specified, the default value is only shown when the `CommandLine.Command.showDefaultValues()` is set `true` on the command. Use this attribute to specify whether the default value for this specific option should always be shown or never be shown, regardless of the command setting.

      Note that picocli 3.2 allows embedding default values by specifying the variable `${DEFAULT-VALUE}` anywhere in the description that ignores this setting.

      Returns:
        whether this option's default value should be shown in the usage help message
      Default:
        picocli.CommandLine.Help.Visibility.ON_DEMAND

  - - #### completionCandidates

          public abstract Class<? extends Iterable<String>> completionCandidates

      Use this attribute to specify an `Iterable<String>` class that generates completion candidates for this option. For map fields, completion candidates should be in `key=value` form.

      Completion candidates are used in bash completion scripts generated by the `picocli.AutoComplete` class. Bash has special completion options to generate file names and host names, and the bash completion scripts generated by `AutoComplete` delegate to these bash built-ins for `@Options` whose `type` is `java.io.File`, `java.nio.file.Path` or `java.net.InetAddress`.

      For `@Options` whose `type` is a Java `enum`, `AutoComplete` can generate completion candidates from the type. For other types, use this attribute to specify completion candidates.

      Returns:
        a class whose instances can iterate over the completion candidates for this option
      Since:
        3.2
      See Also:
        `CommandLine.IFactory`
      Default:
        picocli.CommandLine.NoCompletionCandidates.class

  - - #### interactive

          public abstract boolean interactive

      Set `interactive=true` to make this option prompt the end user for a value (like a password). Only supported for single-value options and `char[]` arrays (no collections, maps or other array types). When running on Java 6 or greater and `echo = false` (the default), this will use the `Console.readPassword()` API to get a value without echoing input to the console, otherwise it will simply read a value from `System.in`.

      For passwords, best security practice is to use type `char[]` instead of `String`, and to to null out the array after use.

      When defined with `arity = "0..1"`, the option can also take a value from the command line. (The user will still be prompted if no option parameter was specified on the command line.) This is useful for commands that need to be run interactively as well as in batch mode.

      Returns:
        whether this option prompts the end user for a value to be entered on the command line
      Since:
        3.5
      Default:
        false

  - - #### echo

          public abstract boolean echo

      Use this attribute to control whether user input for an interactive option is echoed to the console or not. If `echo = true`, the user input is echoed to the console. This attribute is ignored when `interactive = false` (the default).
      Returns:
        whether the user input for an interactive option should be echoed to the console or not
      Since:
        4.6
      See Also:
        `CommandLine.Model.ArgSpec.echo()`
      Default:
        false

  - - #### prompt

          public abstract String prompt

      Use this attribute to customize the text displayed to the end user for an interactive option when asking for user input. When omitted, the displayed text is derived from the option name and the first description line. This attribute is ignored when `interactive = false` (the default).
      Returns:
        the text to display to the end user for an interactive option when asking for user input
      Since:
        4.6
      See Also:
        `CommandLine.Model.ArgSpec.prompt()`
      Default:
        ""

  - - #### descriptionKey

          public abstract String descriptionKey

      ResourceBundle key for this option. If not specified, (and a ResourceBundle exists for this command) an attempt is made to find the option description using any of the option names (without leading hyphens) as key.
      Since:
        3.6
      See Also:
        `CommandLine.Model.ArgSpec.description()`
      Default:
        ""

  - - #### order

          public abstract int order

      When `@Command(sortOptions = false)` is specified, this attribute can be used to control the order in which options are listed in the usage help message.
      Returns:
        the position in the options list at which this option should be shown. Options with a lower number are shown before options with a higher number. Gaps are allowed.
      Since:
        3.9
      Default:
        -1

  - - #### negatable

          public abstract boolean negatable

      (Only for boolean options): set this to automatically add a negative version for this boolean option. For example, for a `--force` option the negative version would be `--no-force`, and for a `-XX:+PrintGCDetails` option, the negative version would be `-XX:-PrintGCDetails`. The synopsis would show `--[no-]force` and `-XX:(+|-)PrintGCDetails`, respectively.

      The form of the negative name can be customized by modifying the regular expressions used by default, or by replacing the default `CommandLine.INegatableOptionTransformer` with a custom implementation entirely.

      Negative option names used to parse the command line are collected when the command is constructed (so any variables in the option names will be resolved at that time). Documentation strings for negatable options are generated on demand when the usage help message is shown.

      Since:
        4.0
      See Also:
        `CommandLine.getNegatableOptionTransformer()`, `CommandLine.setNegatableOptionTransformer(INegatableOptionTransformer)`
      Default:
        false

  - - #### scope

          public abstract CommandLine.ScopeType scope

      Determines on which command(s) this option exists: on this command only (the default), or whether this is a "global" option that is applied to this command and all subcommands, sub-subcommands, etc.
      Since:
        4.3
      Default:
        picocli.CommandLine.ScopeType.LOCAL

  - - #### fallbackValue

          public abstract String fallbackValue

      For options with an optional parameter (for example, `arity = "0..1"`), this value is assigned to the annotated element if the option is specified on the command line without an option parameter.

      This is different from the `defaultValue()`, which is assigned if the option is not specified at all on the command line.

      Using a `fallbackValue` allows applications to distinguish between

      - option was not specified on the command line (default value assigned)
      - option was specified without parameter on the command line (fallback value assigned)
      - option was specified with parameter on the command line (command line argument value assigned)

      This is useful to define options that can function as a boolean "switch" and optionally allow users to provide a (strongly typed) extra parameter value.

      Use the special value `NULL_VALUE` to specify `null` - for options of type `Optional<T>` that will result in the `Optional.empty()` value being assigned when the option name is specified without a parameter on the command line.

      Since:
        4.0
      See Also:
        `CommandLine.Model.OptionSpec.fallbackValue()`
      Default:
        ""

  - - #### mapFallbackValue

          public abstract String mapFallbackValue

      For options of type Map, setting the `mapFallbackValue` to any value allows end user to specify key-only parameters for this option. For example, `-Dkey` instead of `-Dkey=value`.

      The value specified in this annotation is the value that is put into the Map for the user-specified key. Use the special value `NULL_VALUE` to specify `null` - for maps of type `Map<K, Optional<V>>` that will result in `Optional.empty()` values in the map when only the key is specified.

      If no `mapFallbackValue` is set, key-only Map parameters like `-Dkey` are considered invalid user input and cause a `CommandLine.ParameterException` to be thrown.

      Since:
        4.6
      See Also:
        `CommandLine.Model.ArgSpec.mapFallbackValue()`
      Default:
        "__unspecified__"

  - - #### parameterConsumer

          public abstract Class<? extends CommandLine.IParameterConsumer> parameterConsumer

      Optionally specify a custom `IParameterConsumer` to temporarily suspend picocli's parsing logic and process one or more command line arguments in a custom manner. This may be useful when passing arguments through to another program.
      Since:
        4.0
      Default:
        picocli.CommandLine.NullParameterConsumer.class

  - - #### preprocessor

          public abstract Class<? extends CommandLine.IParameterPreprocessor> preprocessor

      Returns the preprocessor for this option.
      Since:
        4.6
      See Also:
        `CommandLine.IParameterPreprocessor`
      Default:
        picocli.CommandLine.NoOpParameterPreprocessor.class