### Real-world JCommander Example with Main Method Source: https://github.com/cbeust/jcommander/blob/master/docs/old-index.html A more complete example demonstrating JCommander usage within a main method, including running a specific logic after parsing. ```java import com.beust.jcommander.Parameter; import com.beust.jcommander.JCommander; class Main { @Parameter(names={"--length", "-l"}) int length; @Parameter(names={"--pattern", "-p"}) int pattern; public static void main(String ... args) { Main main = new Main(); new JCommander(main, args); main.run(); } public void run() { System.out.printf("%d %d", length, pattern); } } ``` -------------------------------- ### Execute Java Main Class with Arguments Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Example of how to execute the `Main` class with command line arguments and the expected output. ```bash $ java Main -l 512 --pattern 2 512 2 ``` -------------------------------- ### Variable Arities Example Source: https://github.com/cbeust/jcommander/blob/master/docs/old-index.html Demonstrates how to handle commands with a variable number of arguments using JCommander. ```java jc.addCommand("commit", commit); jc.parse("-v", "commit", "--amend", "--author=cbeust", "A.java", "B.java"); Assert.assertTrue(cm.verbose); Assert.assertEquals(jc.getParsedCommand(), "commit"); Assert.assertTrue(commit.amend); Assert.assertEquals(commit.author, "cbeust"); Assert.assertEquals(commit.files, List.of("A.java", "B.java")); ``` -------------------------------- ### Parse Main Parameter Example Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Demonstrates parsing command-line arguments where 'files' is the main parameter and '-debug' is a named parameter. ```bash $ java Main -debug 2 file1 file2 ``` -------------------------------- ### Registering Converter Factory Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Example of how to add a converter factory to the JCommander object. ```java ArgsConverterFactory a = new ArgsConverterFactory(); ``` -------------------------------- ### JCommander Usage in Groovy Source: https://github.com/cbeust/jcommander/blob/master/docs/old-index.html Example demonstrating how to use JCommander with Groovy. Uses the 'with' closure for concise object configuration. ```groovy import com.beust.jcommander.* class Args { @Parameter(names = ["-f", "--file"], description = "File to load. Can be specified multiple times.") List file } new Args().with { new JCommander(it, args) file.each { println "file: ${new File(it).name}" } } ``` -------------------------------- ### Parse Command Line Arguments with JCommander Source: https://github.com/cbeust/jcommander/blob/master/docs/old-index.html Instantiate JCommander with your annotated class and the command line arguments to parse them. This example shows basic parsing and assertion. ```java import com.beust.jcommander.JCommander; import java.util.ArrayList; import java.util.List; // Assuming JCommanderExample class is defined as above // import org.testng.Assert; JCommanderExample jct = new JCommanderExample(); String[] argv = { "-log", "2", "-groups", "unit" }; new JCommander(jct, argv); // Assert.assertEquals(jct.verbose.intValue(), 2); ``` -------------------------------- ### File Converter Implementation Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Example implementation of IStringConverter to convert a String to a File object. ```java public class FileConverter implements IStringConverter { @Override public File convert(String value) { return new File(value); } } ``` -------------------------------- ### Example Git Commit Command Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Illustrates a command-line syntax similar to 'git commit --amend -m "Bug fix"'. ```bash $ git commit --amend -m "Bug fix" ``` -------------------------------- ### JCommander Usage in Scala Source: https://github.com/cbeust/jcommander/blob/master/docs/old-index.html Example demonstrating how to use JCommander with Scala. Note the use of 'var' for fields that JCommander assigns to. ```scala import java.io.File import com.beust.jcommander.{JCommander, Parameter} import collection.JavaConversions._ object Main { object Args { @Parameter( names = Array("-f", "--file"), description = "File to load. Can be specified multiple times.") var file: java.util.List[String] = null } def main(args: Array[String]): Unit = { new JCommander(Args, args.toArray: _*) for (filename <- Args.file) { val f = new File(filename) printf("file: %s\n", f.getName) } } } ``` -------------------------------- ### JCommander Arguments in Groovy Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Define and parse command-line arguments using Groovy classes. This example shows how to handle multiple file arguments. ```groovy import com.beust.jcommander.* class Args { @Parameter(names = ["-f", "--file"], description = "File to load. Can be specified multiple times.") List file } new Args().with { JCommander.newBuilder().addObject(it).build().parse(argv) file.each { println "file: ${new File(it).name}" } } ``` -------------------------------- ### Converter Factory Implementation Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Example implementation of IStringConverterFactory to provide a HostPortConverter for the HostPort class. ```java public class Factory implements IStringConverterFactory { public Class> getConverter(Class forType) { if (forType.equals(HostPort.class)) return HostPortConverter.class; else return null; } } ``` -------------------------------- ### Parse Command-Line Arguments with JCommander Source: https://github.com/cbeust/jcommander/blob/master/README.markdown Use JCommander to parse an array of strings (command-line arguments) into your defined parameter object. This example shows how to build and parse arguments. ```java JCommanderTest jct = new JCommanderTest(); String[] argv = { "-log", "2", "-groups", "unit1,unit2,unit3", "-debug", "-Doption=value", "a", "b", "c" }; JCommander.newBuilder() .addObject(jct) .build() .parse(argv); Assert.assertEquals(2, jct.verbose.intValue()); Assert.assertEquals("unit1,unit2,unit3", jct.groups); Assert.assertEquals(true, jct.debug); Assert.assertEquals("value", jct.dynamicParams.get("option")); Assert.assertEquals(List.of("a", "b", "c"), jct.parameters); ``` -------------------------------- ### get Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/Parameterized.html Gets the value of the parameter for a given object. ```APIDOC ## get ### Description Retrieves the value of this parameter from the given object. ### Method `public Object get(Object object)` ### Parameters * **object** (Object) - The object from which to retrieve the parameter value. ``` -------------------------------- ### Example Positive Integer Validator Source: https://github.com/cbeust/jcommander/blob/master/docs/index.html An example implementation of IParameterValidator that ensures a parameter's value is a positive integer. It throws a ParameterException if the value is negative. ```java public class PositiveInteger implements IParameterValidator { public void validate(String name, String value) throws ParameterException { int n = Integer.parseInt(value); if (n < 0) { throw new ParameterException("Parameter " + name + " should be positive (found " + value +")"); } } } ``` -------------------------------- ### Parse Commands with JCommander in Java Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Demonstrates how to build a JCommander object with multiple commands, parse arguments, and inspect the parsed command and its parameters. ```java CommandMain cm = new CommandMain(); CommandAdd add = new CommandAdd(); CommandCommit commit = new CommandCommit(); JCommander jc = JCommander.newBuilder() .addObject(cm) .addCommand("add", add) .addCommand("commit", commit) .build(); jc.parse("-v", "commit", "--amend", "--author=cbeust", "A.java", "B.java"); Assert.assertTrue(cm.verbose); Assert.assertEquals(jc.getParsedCommand(), "commit"); Assert.assertTrue(commit.amend); Assert.assertEquals(commit.author, "cbeust"); Assert.assertEquals(commit.files, List.of("A.java", "B.java")); ``` -------------------------------- ### Build and Parse with Custom Converter Factory Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Demonstrates building a JCommander instance with a custom converter factory and parsing command-line arguments. ```java JCommander jc = JCommander.newBuilder() .addObject(a) .addConverterFactory(new Factory()) .build() .parse("-hostport", "example.com:8080"); Assert.assertEquals(a.hostPort.host, "example.com"); Assert.assertEquals(a.hostPort.port.intValue(), 8080); ``` -------------------------------- ### getName Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/Parameterized.html Gets the name of the parameter. ```APIDOC ## getName ### Description Returns the name of this parameter. ### Method `public String getName()` ``` -------------------------------- ### getGenericType Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/Parameterized.html Gets the generic type of the parameter. ```APIDOC ## getGenericType ### Description Gets the generic type of the parameter. ### Method Signature `public Type getGenericType()` ### Returns * Type - The generic type of the parameter. ``` -------------------------------- ### getType Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/Parameterized.html Gets the class type of the parameter. ```APIDOC ## getType ### Description Returns the `Class` type of this parameter. ### Method `public Class getType()` ``` -------------------------------- ### usage() Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Prints the command-line usage information. ```APIDOC ## usage() ### Description Prints the command-line usage information to the console using the configured formatter. ### Method N/A (Method signature) ### Endpoint N/A ### Parameters None ### Request Example None ### Response None (Prints to console). ``` -------------------------------- ### JCommander.Builder.build Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.Builder.html Builds and returns a new JCommander instance with the configured settings. ```APIDOC ## build() ### Description Builds and returns a new `JCommander` instance with the settings configured in this builder. ### Method `build()` ### Returns A new `JCommander` instance. ``` -------------------------------- ### WrappedParameter.order() Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Method to get the order of a wrapped parameter. ```APIDOC ## WrappedParameter.order() ### Description Method to get the order of a wrapped parameter. ### Method Method in class `com.beust.jcommander.WrappedParameter` ``` -------------------------------- ### EnvironmentVariableDefaultProvider Constructor (no args) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Constructor for EnvironmentVariableDefaultProvider that uses default settings. ```APIDOC ## EnvironmentVariableDefaultProvider Constructor (no args) ### Description Constructor for class `com.beust.jcommander.defaultprovider.EnvironmentVariableDefaultProvider`. Creates a default provider reading the environment variable `JCOMMANDER_OPTS` using the prefixes pattern `-/`. ### Method `EnvironmentVariableDefaultProvider()` ### Endpoint `EnvironmentVariableDefaultProvider()` ``` -------------------------------- ### WrappedParameter names() Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Method to get the names associated with a WrappedParameter. ```APIDOC ## names() ### Description Returns the names associated with this `WrappedParameter`. ### Method `names()` ### Endpoint N/A (Java method) ``` -------------------------------- ### JCommander.getColumnSize Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Gets the current console column size setting. ```APIDOC ## getColumnSize() ### Description Gets the current console column size setting used by JCommander for formatting output, such as help messages. ### Method com.beust.jcommander.JCommander.getColumnSize() ``` -------------------------------- ### getColumnSize() Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.html Gets the current column size used for formatting help messages. ```APIDOC ## getColumnSize() ### Description Gets the current column size used for formatting help messages. ### Method int ### Returns The column size. ``` -------------------------------- ### build Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.Builder.html Builds and returns a configured JCommander instance based on the builder's settings. ```APIDOC ## build ### Description Builds and returns a configured JCommander instance based on the builder's settings. ### Method Signature public JCommander build() ### Returns A new JCommander instance configured with the settings provided to the builder. ``` -------------------------------- ### Generating and Customizing Help Text with JCommander Source: https://context7.com/cbeust/jcommander/llms.txt Call usage() on a JCommander instance to print generated help text to stdout. You can also capture usage as a string using a StringBuilder for custom rendering or testing. ```java import com.beust.jcommander.*; class CliArgs { @Parameter(names = {"--output", "-o"}, description = "Output file", order = 0, placeholder = "") String output; @Parameter(names = "--count", description = "Repetition count", order = 1, defaultValueDescription = "defaults to 1") int count = 1; @Parameter(names = "--dry-run", description = "Preview without applying changes", order = 2) boolean dryRun; } CliArgs args = new CliArgs(); JCommander jc = JCommander.newBuilder() .addObject(args) .programName("mytool") .columnSize(80) .build(); // Print usage to stdout jc.usage(); // Capture usage as string (e.g., for testing or custom rendering) StringBuilder sb = new StringBuilder(); jc.usage(sb); System.out.println(sb); ``` -------------------------------- ### EnvironmentVariableDefaultProvider Constructor (with args) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Constructor for EnvironmentVariableDefaultProvider that allows specifying environment variable and prefix pattern. ```APIDOC ## EnvironmentVariableDefaultProvider Constructor (with args) ### Description Constructor for class `com.beust.jcommander.defaultprovider.EnvironmentVariableDefaultProvider`. Creates a default provider reading the specified environment variable using the specified prefixes pattern. ### Method `EnvironmentVariableDefaultProvider(String, String)` ### Parameters * **arg0** (String) - Description not available * **arg1** (String) - Description not available ``` -------------------------------- ### startsWith Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/Strings.html Checks if a string starts with a specified prefix, with optional case sensitivity. ```APIDOC ## startsWith(String s, String with, boolean isCaseSensitive) ### Description Checks if a string starts with a specified prefix, with optional case sensitivity. ### Method public static boolean startsWith(String s, String with, boolean isCaseSensitive) ### Parameters #### Path Parameters * **s** (String) - The string to check. * **with** (String) - The prefix to look for. * **isCaseSensitive** (boolean) - Whether the comparison should be case-sensitive. ### Returns * **boolean** - true if the string starts with the prefix, false otherwise. ``` -------------------------------- ### startsWith Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/Strings.html Checks if a string starts with a specified prefix, with optional case sensitivity. ```APIDOC ## startsWith ### Description Checks if a string starts with a specified prefix, with optional case sensitivity. ### Method Signature `static boolean startsWith(String s, String with, boolean isCaseSensitive)` ### Parameters * **s** (String) - The string to check. * **with** (String) - The prefix to look for. * **isCaseSensitive** (boolean) - `true` to perform a case-sensitive comparison, `false` otherwise. ### Return Value `true` if the string starts with the prefix, `false` otherwise. ``` -------------------------------- ### Build JCommander Project Source: https://github.com/cbeust/jcommander/blob/master/README.markdown Build the JCommander project using Gradle. This command assembles the project artifacts. ```bash ./gradlew assemble ``` -------------------------------- ### usage(String commandName, StringBuilder out) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.html Stores the help information for a command in a StringBuilder. ```APIDOC ## usage(String commandName, StringBuilder out) ### Description Stores the help information for the command in the passed string builder. ### Method public void usage(String commandName, StringBuilder out) ``` -------------------------------- ### EnvironmentVariableDefaultProvider Constructors Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/defaultprovider/EnvironmentVariableDefaultProvider.html Details on how to create an instance of EnvironmentVariableDefaultProvider. ```APIDOC ## EnvironmentVariableDefaultProvider() ### Description Creates a default provider reading the environment variable `JCOMMANDER_OPTS` using the prefixes pattern `-/`. ### Method public EnvironmentVariableDefaultProvider() ``` ```APIDOC ## EnvironmentVariableDefaultProvider(String environmentVariableName, String optionPrefixes) ### Description Creates a default provider reading the specified environment variable using the specified prefixes pattern. ### Parameters #### Path Parameters - **environmentVariableName** (String) - Required - The name of the environment variable to read (e. g. "JCOMMANDER_OPTS"). Must not be `null`. - **optionPrefixes** (String) - Required - A set of characters used to indicate the start of an option (e. g. "-/" if option names may start with either dash or slash). Must not be `null`. ``` -------------------------------- ### Configuration and Options Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.html Methods for configuring JCommander's behavior regarding options and parameter handling. ```APIDOC ## setAcceptUnknownOptions(boolean b) ### Description Sets whether to accept unknown options. ### Method void ### Parameters - **b** (boolean) - True to accept unknown options, false otherwise. ``` ```APIDOC ## setAllowAbbreviatedOptions(boolean b) ### Description Sets whether to allow abbreviated options. ### Method void ### Parameters - **b** (boolean) - True to allow abbreviated options, false otherwise. ``` ```APIDOC ## setAllowParameterOverwriting(boolean b) ### Description Sets whether parameter overwriting is allowed. ### Method void ### Parameters - **b** (boolean) - True to allow parameter overwriting, false otherwise. ``` ```APIDOC ## setAtFileCharset(Charset charset) ### Description Sets the charset used to expand `@files`. ### Method void ### Parameters - **charset** (Charset) - The charset to use for expanding @files. ``` ```APIDOC ## setCaseSensitiveOptions(boolean b) ### Description Sets whether options are case-sensitive. ### Method void ### Parameters - **b** (boolean) - True for case-sensitive options, false otherwise. ``` ```APIDOC ## setColumnSize(int columnSize) ### Description Sets the column size for usage formatting. ### Method void ### Parameters - **columnSize** (int) - The desired column size. ``` ```APIDOC ## setConsole(Console console) ### Description Sets the console implementation to use for input/output. ### Method void ### Parameters - **console** (Console) - The Console implementation. ``` -------------------------------- ### Invoke Integer Parameter Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Example of invoking an integer parameter with a valid integer value. ```bash java Main -log 3 ``` -------------------------------- ### usage(StringBuilder out) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.html Stores the overall help information in a StringBuilder. ```APIDOC ## usage(StringBuilder out) ### Description Stores the help in the passed string builder. ### Method public void usage(StringBuilder out) ``` -------------------------------- ### usage(String commandName, StringBuilder out, String indent) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/IUsageFormatter.html Stores the help for the specified command in the provided StringBuilder, indenting each line with the given indent string. ```APIDOC ## usage(String commandName, StringBuilder out, String indent) ### Description Stores the help for the command in the passed string builder, indenting every line with "indent". ### Parameters #### Path Parameters - **commandName** (String) - Description of the command to get help for. - **out** (StringBuilder) - The StringBuilder to append the usage information to. - **indent** (String) - The string to use for indenting each line of the usage information. ``` -------------------------------- ### JCommander.setAllowAbbreviatedOptions(boolean) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Determines if options can be abbreviated. For example, if 'verbose' is an option, '-v' might be accepted if this is set to true. ```APIDOC ## setAllowAbbreviatedOptions(boolean) ### Description Sets whether abbreviated options are allowed. ### Method setAllowAbbreviatedOptions(boolean allowAbbreviatedOptions) ### Class com.beust.jcommander.JCommander ``` -------------------------------- ### JCommander.Builder build() Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Builds the JCommander instance. ```APIDOC ## build() ### Description Builds the JCommander instance. ### Method build ### Class com.beust.jcommander.JCommander.Builder ``` -------------------------------- ### JCommander.getOptions() Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Retrieves the options configured for JCommander. ```APIDOC ## getOptions() ### Description Retrieves the options configured for JCommander. ### Method Method ### Class com.beust.jcommander.JCommander ``` -------------------------------- ### Invoke Boolean Parameter with Arity 1 Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Examples of how to invoke a boolean parameter with arity 1, specifying 'true' or 'false'. ```bash program -debug true program -debug false ``` -------------------------------- ### JCommander Constructors Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.html Provides details on the various ways to instantiate a JCommander object, allowing for different initialization strategies. ```APIDOC ## JCommander() ### Description Creates a new un-configured JCommander object. ### Method public ### Parameters None ``` ```APIDOC ## JCommander(Object object) ### Description Creates a JCommander object with a specified object that is expected to contain `Parameter` annotations. ### Method public ### Parameters * **object** (Object) - The arg object expected to contain [`Parameter`](Parameter.html "annotation interface in com.beust.jcommander") annotations. ``` ```APIDOC ## JCommander(Object object, ResourceBundle bundle) ### Description Creates a JCommander object with a specified object and a `ResourceBundle` for descriptions. ### Method public ### Parameters * **object** (Object) - The arg object expected to contain [`Parameter`](Parameter.html "annotation interface in com.beust.jcommander") annotations. * **bundle** (ResourceBundle) - The bundle to use for the descriptions. Can be null. ``` ```APIDOC ## JCommander(Object object, ResourceBundle bundle, String... args) ### Description Creates a JCommander object with a specified object, a `ResourceBundle`, and command-line arguments. ### Method public ### Parameters * **object** (Object) - The arg object expected to contain [`Parameter`](Parameter.html "annotation interface in com.beust.jcommander") annotations. * **bundle** (ResourceBundle) - The bundle to use for the descriptions. Can be null. * **args** (String...) - The arguments to parse (optional). ``` ```APIDOC ## JCommander(Object object, String... args) ### Description Deprecated. Construct a JCommander instance first and then call parse() on it. ### Method @Deprecated public ### Parameters * **object** (Object) - The arg object expected to contain [`Parameter`](Parameter.html "annotation interface in com.beust.jcommander") annotations. * **args** (String...) - The arguments to parse (optional). ``` -------------------------------- ### usage (commandName, out) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/IUsageFormatter.html Stores the help information for a specific command into the provided StringBuilder. ```APIDOC ## usage(String commandName, StringBuilder out) ### Description Store the help for the command in the passed string builder. ### Method Signature `void usage(String commandName, StringBuilder out)` ### Parameters #### Path Parameters - **commandName** (String) - The name of the command for which to store help. - **out** (StringBuilder) - The StringBuilder to which the help information will be appended. ``` -------------------------------- ### usage Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/DefaultUsageFormatter.html Prints the command usage to the console. ```APIDOC ## usage(String commandName) ### Description Prints the usage to JCommander.getConsole() on the underlying commander instance. ### Parameters #### Path Parameters - **commandName** (String) - Description not available ``` -------------------------------- ### Custom Usage Formatter in Java Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Customize the output of JCommander#usage() by subclassing IUsageFormatter. This example shows a formatter that prints only parameter names. ```java class ParameterNamesUsageFormatter implements IUsageFormatter { // Extend other required methods as seen in DefaultUsageFormatter // This is the method which does the actual output formatting public void usage(StringBuilder out, String indent) { if (commander.getDescriptions() == null) { commander.createDescriptions(); } // Create a list of the parameters List params = Lists.newArrayList(); params.addAll(commander.getFields().values()); // Append all the parameter names if (params.size() > 0) { out.append("Options:\n"); for (ParameterDescription pd : params) { out.append(pd.getNames()).append("\n"); } } } } ``` -------------------------------- ### usage (out) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/IUsageFormatter.html Stores the help information into the provided StringBuilder. ```APIDOC ## usage(StringBuilder out) ### Description Store the help in the passed string builder. ### Method Signature `void usage(StringBuilder out)` ### Parameters #### Path Parameters - **out** (StringBuilder) - The StringBuilder to which the help information will be appended. ``` -------------------------------- ### getOptions() Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.html Retrieves the options configuration for JCommander. ```APIDOC ## getOptions() ### Description Retrieves the options configuration for JCommander. ### Method public JCommander.Options getOptions() ``` -------------------------------- ### InstantConverter Constructor Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/converters/InstantConverter.html Initializes a new instance of the InstantConverter class. ```APIDOC ## InstantConverter Constructor ### Description Initializes a new instance of the InstantConverter class. ### Signature public InstantConverter(String optionName) ### Parameters * **optionName** (String) - The name of the option this converter is associated with. ``` -------------------------------- ### Parse Command Line with Multiple Hosts Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Demonstrates parsing a command line with multiple values for the same parameter. ```bash $ java Main -host host1 -verbose -host host2 ``` ```bash $ java Main -hosts host1,host2 ``` -------------------------------- ### Read arguments from a file using @ syntax Source: https://context7.com/cbeust/jcommander/llms.txt Prefix an argument with '@' to have JCommander read the file and inline its contents as additional arguments. Lines starting with '#' and empty lines are ignored. To disable this feature, use expandAtSign(false). ```java // /tmp/myapp.opts: // --host // example.com // --port // 9090 // # this is a comment // --verbose import com.beust.jcommander.*; class Opts { @Parameter(names = "--host") String host; @Parameter(names = "--port") int port; @Parameter(names = "--verbose") boolean verbose; } Opts opts = new Opts(); JCommander.newBuilder() .addObject(opts) .build() .parse("@/tmp/myapp.opts"); System.out.println(opts.host); // example.com System.out.println(opts.port); // 9090 System.out.println(opts.verbose); // true // Disable @ expansion if needed: JCommander jc2 = JCommander.newBuilder() .addObject(new Opts()) .expandAtSign(false) .build(); ``` -------------------------------- ### Implement IParametersValidator for Mutual Exclusion Source: https://github.com/cbeust/jcommander/blob/master/docs/index.html Implement the IParametersValidator interface to define custom validation logic. This example ensures that mutually exclusive boolean options like --quiet and --verbose are not enabled simultaneously. Throw a ParameterException if validation fails. ```java void validate(Map parameters) throws ParameterException; ``` ```java public static class QuietAndVerboseAreMutualExclusive implements IParametersValidator { @Override public void validate(Map parameters) throws ParameterException { if (parameters.get("--quiet") == TRUE && parameters.get("--verbose") == TRUE) throw new ParameterException("--quiet and --verbose are mutually exclusive"); } } ``` -------------------------------- ### Using Delegate Parameters in JCommander Source: https://github.com/cbeust/jcommander/blob/master/docs/index.html Demonstrates how to use a delegate parameter with JCommander. Add a MainParams object to your JCommander configuration to utilize the delegate. ```java @Parameter(names = "-v") private boolean verbose; @ParametersDelegate private Delegate delegate = new Delegate(); } ``` ```java MainParams p = new MainParams(); JCommander.newBuilder().addObject(p).build() .parse("-v", "-port", "1234"); Assert.assertTrue(p.isVerbose); Assert.assertEquals(p.delegate.port, 1234); ``` -------------------------------- ### usage(StringBuilder out, String indent) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/IUsageFormatter.html Stores the help information in the provided StringBuilder, applying the specified indentation to each line. ```APIDOC ## usage(StringBuilder out, String indent) ### Description Stores the help in the passed string builder, with the argument indentation. ### Parameters #### Path Parameters - **out** (StringBuilder) - The StringBuilder to append the usage information to. - **indent** (String) - The string to use for indenting each line of the usage information. ``` -------------------------------- ### Help Parameter in Java Source: https://github.com/cbeust/jcommander/blob/master/docs/old-index.html Use `help = true` for parameters that display help or usage information. This prevents JCommander from throwing an error if required parameters are missing when help is requested. ```java @Parameter(names = "--help", help = true) private boolean help; ``` -------------------------------- ### JCommander.getUnknownOptions() Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Retrieves the list of unknown options encountered by JCommander. ```APIDOC ## getUnknownOptions() ### Description Retrieves the list of unknown options encountered by JCommander. ### Method Method ### Class com.beust.jcommander.JCommander ``` -------------------------------- ### usage (commandName, out, indent) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/IUsageFormatter.html Stores the help information for a specific command into the provided StringBuilder with specified indentation. ```APIDOC ## usage(String commandName, StringBuilder out, String indent) ### Description Store the help for the command in the passed string builder, indenting every line with "indent". ### Method Signature `void usage(String commandName, StringBuilder out, String indent)` ### Parameters #### Path Parameters - **commandName** (String) - The name of the command for which to store help. - **out** (StringBuilder) - The StringBuilder to which the help information will be appended. - **indent** (String) - The indentation string to apply to each line of the help message. ``` -------------------------------- ### JCommander.Builder Methods Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.Builder.html This section details the various methods available on the JCommander.Builder class to configure JCommander. ```APIDOC ## resourceBundle ### Description Sets the `ResourceBundle` to use for looking up descriptions. Set this to `null` to use description text directly. ### Method Signature `public JCommander.Builder resourceBundle(ResourceBundle bundle)` ``` ```APIDOC ## args ### Description Sets the command-line arguments to be parsed. ### Method Signature `public JCommander.Builder args(String[] args)` ``` ```APIDOC ## console ### Description Sets the console implementation to use for input/output operations. ### Method Signature `public JCommander.Builder console(Console console)` ``` ```APIDOC ## expandAtSign ### Description Disables expanding `@file`. JCommander supports the `@file` syntax, which allows you to put all your options into a file and pass this file as parameter. ### Method Signature `public JCommander.Builder expandAtSign(Boolean expand)` ``` ```APIDOC ## programName ### Description Set the program name, which is used only in the usage information. ### Method Signature `public JCommander.Builder programName(String name)` ``` ```APIDOC ## columnSize ### Description Sets the column size for formatting output, such as usage information. ### Method Signature `public JCommander.Builder columnSize(int columnSize)` ``` ```APIDOC ## defaultProvider ### Description Define the default provider for this JCommander instance. ### Method Signature `public JCommander.Builder defaultProvider(IDefaultProvider provider)` ``` ```APIDOC ## addConverterFactory ### Description Adds a factory to lookup string converters. The added factory is used prior to previously added factories. ### Parameters * `factory` - the factory determining string converters ### Method Signature `public JCommander.Builder addConverterFactory(IStringConverterFactory factory)` ``` ```APIDOC ## verbose ### Description Sets the verbosity level for JCommander output. ### Method Signature `public JCommander.Builder verbose(int verbose)` ``` ```APIDOC ## allowAbbreviatedOptions ### Description Enables or disables the allowance of abbreviated options. ### Method Signature `public JCommander.Builder allowAbbreviatedOptions(boolean b)` ``` ```APIDOC ## acceptUnknownOptions ### Description Enables or disables the acceptance of unknown options. ### Method Signature `public JCommander.Builder acceptUnknownOptions(boolean b)` ``` ```APIDOC ## allowParameterOverwriting ### Description Enables or disables the overwriting of parameters. ### Method Signature `public JCommander.Builder allowParameterOverwriting(boolean b)` ``` ```APIDOC ## atFileCharset ### Description Sets the character set to use when reading files specified with the `@file` syntax. ### Method Signature `public JCommander.Builder atFileCharset(Charset charset)` ``` ```APIDOC ## addConverterInstanceFactory ### Description Adds a factory for creating converter instances. ### Method Signature `public JCommander.Builder addConverterInstanceFactory(IStringConverterInstanceFactory factory)` ``` ```APIDOC ## addCommand ### Description Adds a command to JCommander. ### Method Signature `public JCommander.Builder addCommand(Object command)` ``` ```APIDOC ## addCommand with aliases ### Description Adds a command to JCommander with a specific name and aliases. ### Method Signature `public JCommander.Builder addCommand(String name, Object command, String... aliases)` ``` -------------------------------- ### usage(String commandName) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/DefaultUsageFormatter.html Prints the usage information for a specific command to the console associated with the JCommander instance. ```APIDOC ## usage(String commandName) ### Signature public final void usage(String commandName) ### Description Prints the usage to `JCommander.getConsole()` on the underlying commander instance for the specified command. ### Implements `IUsageFormatter.usage(java.lang.String)` ``` -------------------------------- ### Main Class with JCommander Parsing Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc A main class demonstrating how to define parameters and parse them using JCommander. The `run` method is called after parsing. ```java class Main { @Parameter(names={"--length", "-l"}) int length; @Parameter(names={"--pattern", "-p"}) int pattern; public static void main(String ... argv) { Main main = new Main(); JCommander.newBuilder() .addObject(main) .build() .parse(argv); main.run(); } public void run() { System.out.printf("%d %d", length, pattern); } } ``` -------------------------------- ### JCommander.Builder.args Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.Builder.html Sets the arguments to be parsed. ```APIDOC ## args(String[] args) ### Description Sets the arguments to be parsed by JCommander. ### Method `args(String[] args)` ### Parameters * **args** (String[]) - The array of arguments to set. ``` -------------------------------- ### Constructing JCommander with Builder API Source: https://context7.com/cbeust/jcommander/llms.txt Use JCommander.newBuilder() for a fluent API to construct JCommander instances. Configure program name, default providers, converters, and accept unknown or abbreviated options. The 'args' method can be used to provide command-line arguments directly. ```java import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; class Config { @Parameter(names = "--port", description = "Server port") int port = 8080; @Parameter(names = "--env", description = "Environment") String env = "production"; } Config cfg = new Config(); JCommander jc = JCommander.newBuilder() .addObject(cfg) .programName("server") .allowAbbreviatedOptions(true) // --po 9090 is accepted .acceptUnknownOptions(true) // unknown flags are silently collected .columnSize(100) .args(new String[]{"--port", "9090", "--env", "staging"}) .build(); System.out.println(cfg.port); // 9090 System.out.println(cfg.env); // staging System.out.println(jc.getUnknownOptions()); // [] ``` -------------------------------- ### JCommander.getMainParameterDescription() Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Retrieves the description of the main parameter. ```APIDOC ## getMainParameterDescription() ### Description Retrieves the description of the main parameter. ### Method Method ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) - **mainParameterDescription** (ParameterDescription) - The description of the main parameter. ``` -------------------------------- ### JCommander.getDescriptions() Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Retrieves a map of command names to their descriptions. ```APIDOC ## getDescriptions() ### Description Retrieves a map of command names to their descriptions. ### Method Method ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) - **descriptions** (Map) - A map where keys are command names and values are their descriptions. ``` -------------------------------- ### ParameterDescription Constructor (Object, DynamicParameter, Parameterized, ResourceBundle, JCommander) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Constructor for ParameterDescription. ```APIDOC ## ParameterDescription(Object, DynamicParameter, Parameterized, ResourceBundle, JCommander) ### Description Constructor for `ParameterDescription`. ### Method Constructor ### Parameters * **Object** - Description of the object parameter * **DynamicParameter** - Description of the DynamicParameter parameter * **Parameterized** - Description of the Parameterized parameter * **ResourceBundle** - Description of the ResourceBundle parameter * **JCommander** - Description of the JCommander parameter ``` -------------------------------- ### EnvironmentVariableDefaultProvider Constructors Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/defaultprovider/EnvironmentVariableDefaultProvider.html Constructors for EnvironmentVariableDefaultProvider. ```APIDOC ## EnvironmentVariableDefaultProvider() ### Description Creates a default provider reading the environment variable `JCOMMANDER_OPTS` using the prefixes pattern `-/`. ### Constructor `EnvironmentVariableDefaultProvider()` ``` ```APIDOC ## EnvironmentVariableDefaultProvider(String environmentVariableName, String optionPrefixes) ### Description Creates a default provider reading the specified environment variable using the specified prefixes pattern. ### Parameters #### Path Parameters - **environmentVariableName** (String) - Required - The name of the environment variable to read. - **optionPrefixes** (String) - Required - The pattern of prefixes to identify options. ``` -------------------------------- ### JCommander Builder Methods Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.Builder.html This section outlines the various methods available on the JCommander.Builder class to configure JCommander instances before they are built. ```APIDOC ## JCommander.Builder Methods ### Description Methods to configure JCommander instances. ### Methods * `addObject(Object o)`: Adds an object to be parsed for arguments. If the object is an array or iterable, its children are added. * `columnSize(int columnSize)`: Sets the column size for usage output. * `console(Console console)`: Sets the console to be used for input/output. * `defaultProvider(IDefaultProvider provider)`: Defines the default provider for this instance. * `expandAtSign(Boolean expand)`: Disables expanding `@file`. * `programName(String name)`: Sets the program name, used only in the usage message. * `resourceBundle(ResourceBundle bundle)`: Sets the `ResourceBundle` for looking up descriptions. * `usageFormatter(IUsageFormatter usageFormatter)`: Sets a custom usage formatter. * `verbose(int verbose)`: Sets the verbosity level. ``` -------------------------------- ### JCommander Constructors Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.html This section details the various constructors available for the JCommander class, allowing for different initialization scenarios. ```APIDOC ## Constructors ### `JCommander()` Creates a new un-configured JCommander object. ### `JCommander(Object object)` Constructs a JCommander instance with a single object containing annotated parameters. ### `JCommander(Object object, String... args)` Deprecated. Constructs a JCommander instance first and then calls parse() on it. ### `JCommander(Object object, ResourceBundle bundle)` Constructs a JCommander instance with a single object and a ResourceBundle for internationalization. ### `JCommander(Object object, ResourceBundle bundle, String... args)` Constructs a JCommander instance with a single object, a ResourceBundle, and command-line arguments. ``` -------------------------------- ### JCommander.Builder.acceptUnknownOptions Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.Builder.html Configures whether to accept unknown options. ```APIDOC ## acceptUnknownOptions(boolean b) ### Description Configures whether to accept unknown options. ### Method `acceptUnknownOptions(boolean b)` ### Returns Returns the current `Builder` instance for chaining. ``` -------------------------------- ### JCommander.Builder Constructor Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.Builder.html Initializes a new instance of the JCommander.Builder class. ```APIDOC ## Builder() ### Description Initializes a new instance of the `Builder` class. ### Constructor `Builder()` ``` -------------------------------- ### usage (out, indent) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/IUsageFormatter.html Stores the help information into the provided StringBuilder with specified indentation. ```APIDOC ## usage(StringBuilder out, String indent) ### Description Stores the help in the passed string builder, with the argument indentation. ### Method Signature `void usage(StringBuilder out, String indent)` ### Parameters #### Path Parameters - **out** (StringBuilder) - The StringBuilder to which the help information will be appended. - **indent** (String) - The indentation string to apply to each line of the help message. ``` -------------------------------- ### ParameterDescription Constructor (Object, Parameter, Parameterized, ResourceBundle, JCommander) Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Constructor for ParameterDescription. ```APIDOC ## ParameterDescription(Object, Parameter, Parameterized, ResourceBundle, JCommander) ### Description Constructor for `ParameterDescription`. ### Method Constructor ### Parameters * **Object** - Description of the object parameter * **Parameter** - Description of the Parameter parameter * **Parameterized** - Description of the Parameterized parameter * **ResourceBundle** - Description of the ResourceBundle parameter * **JCommander** - Description of the JCommander parameter ``` -------------------------------- ### JDK6Console Constructor Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/internal/JDK6Console.html Constructs a new JDK6Console instance. ```APIDOC ## JDK6Console Constructor ### Description Constructs a new JDK6Console instance. ### Signature `public JDK6Console(Object console) throws Exception` ### Parameters * **console** (Object) - The console object to use. ``` -------------------------------- ### Parse Command Line Arguments with JCommander Source: https://github.com/cbeust/jcommander/blob/master/docs/index.adoc Instantiate a JCommander object, add your annotated object, build the commander, and then parse the command line arguments. ```java Args args = new Args(); String[] argv = { "-log", "2", "-groups", "unit" }; JCommander.newBuilder() .addObject(args) .build() .parse(argv); Assert.assertEquals(args.verbose.intValue(), 2); ``` -------------------------------- ### usage Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/DefaultUsageFormatter.html Stores the command usage in a StringBuilder with indentation. ```APIDOC ## usage(StringBuilder out, String indent) ### Description Stores the usage in the argument string builder, with the argument indentation. ### Parameters #### Path Parameters - **out** (StringBuilder) - Description not available - **indent** (String) - Description not available ``` -------------------------------- ### JDK6Console Class Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Console implementation for JDK 6. ```APIDOC ## Class: JDK6Console ### Description Console implementation for JDK 6. ### Constructors - **JDK6Console(Object)**: Constructor for JDK6Console. ``` -------------------------------- ### Creating new LinkedList instances Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/internal/Lists.html These methods provide ways to create new LinkedList instances. ```APIDOC ## newLinkedList() ### Description Creates a new, empty LinkedList. ### Method `static LinkedList newLinkedList()` ### Returns An empty LinkedList. ``` ```APIDOC ## newLinkedList(Collection c) ### Description Creates a new LinkedList containing the elements of the specified collection. ### Method `static LinkedList newLinkedList(Collection c)` ### Parameters * **c** (Collection) - The collection whose elements are to be placed into this LinkedList. ### Returns A LinkedList containing the elements of the specified collection. ``` -------------------------------- ### InstantConverter Methods Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/converters/InstantConverter.html This section details the methods available in the InstantConverter class for parsing and handling Instant values. ```APIDOC ## InstantConverter Converter to `Instant`. ### Methods #### `protected Instant parse(String value, DateTimeFormatter formatter)` Parse the value using the specified formatter. #### `protected Set supportedFormats()` Supported formats for this type, e.g. ``` -------------------------------- ### usage Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/DefaultUsageFormatter.html Stores the command usage in a StringBuilder. ```APIDOC ## usage(StringBuilder out) ### Description Store the usage in the argument string builder. ### Parameters #### Path Parameters - **out** (StringBuilder) - Description not available ``` -------------------------------- ### JCommander.ProgramName Methods Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/JCommander.ProgramName.html This section details the methods available for the JCommander.ProgramName class, including methods for retrieving names and for object comparison. ```APIDOC ## getName ### Description Retrieves the name of the program or command. ### Method ```java public String getName() ``` ## getDisplayName ### Description Retrieves the display name of the program or command. ### Method ```java public String getDisplayName() ``` ## hashCode ### Description Returns a hash code value for the object. ### Method ```java public int hashCode() ``` ## equals ### Description Indicates whether some other object is "equal to" this one. ### Method ```java public boolean equals(Object obj) ``` ``` -------------------------------- ### UnixStyleUsageFormatter Constructor Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/UnixStyleUsageFormatter.html Initializes a new instance of the UnixStyleUsageFormatter class. ```APIDOC ## UnixStyleUsageFormatter(JCommander commander) ### Description Constructs a new UnixStyleUsageFormatter associated with the given JCommander instance. ### Constructor `UnixStyleUsageFormatter(JCommander commander)` ### Parameters * **commander** (JCommander) - The JCommander instance to associate with this formatter. ``` -------------------------------- ### UnixStyleUsageFormatter Constructor Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/UnixStyleUsageFormatter.html Initializes a new instance of the UnixStyleUsageFormatter class. ```APIDOC ## UnixStyleUsageFormatter Constructor ### Signature public UnixStyleUsageFormatter(JCommander commander) ### Description Constructs a new UnixStyleUsageFormatter with the specified JCommander instance. ``` -------------------------------- ### Creating new ArrayList instances Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/com/beust/jcommander/internal/Lists.html These methods allow for the creation of new ArrayList instances with different initializations. ```APIDOC ## newArrayList() ### Description Creates a new, empty ArrayList. ### Method `static List newArrayList()` ### Returns An empty ArrayList. ``` ```APIDOC ## newArrayList(int size) ### Description Creates a new ArrayList with the specified initial capacity. ### Method `static List newArrayList(int size)` ### Parameters * **size** (int) - The initial capacity of the ArrayList. ### Returns An empty ArrayList with the specified initial capacity. ``` ```APIDOC ## newArrayList(Collection c) ### Description Creates a new ArrayList containing the elements of the specified collection. ### Method `static List newArrayList(Collection c)` ### Parameters * **c** (Collection) - The collection whose elements are to be placed into this ArrayList. ### Returns An ArrayList containing the elements of the specified collection. ``` ```APIDOC ## newArrayList(K... c) ### Description Creates a new ArrayList containing the specified varargs elements. ### Method `static List newArrayList(K... c)` ### Parameters * **c** (K...) - The elements to be included in the ArrayList. ### Returns An ArrayList containing the specified elements. ``` -------------------------------- ### JCommander.getParameters() Source: https://github.com/cbeust/jcommander/blob/master/docs/apidocs/index-all.html Retrieves the list of parameters configured for JCommander. ```APIDOC ## getParameters() ### Description Retrieves the list of parameters configured for JCommander. ### Method Method ### Class com.beust.jcommander.JCommander ```