### Get Example Usage with Required Options Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/types.md Generates an example command-line string that includes only the required options. This can be helpful for demonstrating minimal valid command structures. ```java // Print example with only required options String example = parser.printExample(OptionHandlerFilter.REQUIRED); ``` -------------------------------- ### Print Example with Localization Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-CmdLineParser.md Generates an example of command-line usage, incorporating localization based on the provided ResourceBundle. ```java public String printExample(OptionHandlerFilter filter, ResourceBundle rb) ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/configuration-and-utilities.md A comprehensive example demonstrating advanced args4j configuration, including custom option sorting, usage width, and at-file syntax. It parses arguments and prints usage information. ```java import org.kohsuke.args4j.*; import java.util.Comparator; import java.io.File; public class AdvancedApp { @Option(name = "-required") private String required; @Option(name = "-optional") private String optional; @Option(name = "-hidden", hidden = true) private String hidden; public static void main(String[] args) throws CmdLineException { AdvancedApp app = new AdvancedApp(); // Create custom properties Comparator sorter = (h1, h2) -> { // Required options first boolean req1 = h1.option.required(); boolean req2 = h2.option.required(); if (req1 != req2) return req1 ? -1 : 1; // Then alphabetical return h1.option.toString().compareTo(h2.option.toString()); }; ParserProperties props = ParserProperties.defaults() .withUsageWidth(100) // Wider output .withAtSyntax(true) // Enable @file syntax .withShowDefaults(true) // Show defaults .withOptionValueDelimiter("=") // Use = in display .withOptionSorter(sorter); // Custom sorting CmdLineParser parser = new CmdLineParser(app, props); try { parser.parseArgument(args); // Print usage with custom filter System.out.println("Usage examples:"); System.out.println("1. All options:"); parser.printUsage(System.out, null, OptionHandlerFilter.ALL); System.out.println("\n2. Public options only:"); parser.printUsage(System.out, null, OptionHandlerFilter.PUBLIC); System.out.println("\n3. Example command:"); System.out.println("app" + parser.printExample(OptionHandlerFilter.REQUIRED)); } catch (CmdLineException e) { System.err.println("Error: " + e.getMessage()); parser.printUsage(System.err); System.exit(1); } } } ``` -------------------------------- ### Print Example Usage Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/quick-reference.md Generate an example command line, including required options, using 'printExample'. This is useful for demonstrating how to invoke the application. ```java String example = parser.printExample(OptionHandlerFilter.REQUIRED); System.err.println("Usage: java App" + example + " files..."); ``` -------------------------------- ### Generate Command-Line Example String Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-CmdLineParser.md Generates a string representing a command-line example, useful for constructing help messages. The filter controls which options are included in the example. The output is prefixed with a space if options are present. ```java String example = parser.printExample(OptionHandlerFilter.REQUIRED); System.err.println("java MyApp" + example + " "); ``` -------------------------------- ### Option with Dependencies Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-Annotations.md Example of an option that depends on another option being present. ```java @Option(name="-server") private String server; @Option(name="-port", depends={"-server"}, usage="port (requires -server)") private int port; ``` -------------------------------- ### Print Example (Deprecated) Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-CmdLineParser.md This method is deprecated. Use printExample(OptionHandlerFilter) instead for generating localized examples. ```java public String printExample(ExampleMode mode) ``` -------------------------------- ### Generate Example Command Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/configuration-and-utilities.md Generates an example command string, typically showing required options. This can be used to illustrate how to invoke the application. ```java String example = parser.printExample(OptionHandlerFilter.REQUIRED); ``` -------------------------------- ### printExample(OptionHandlerFilter filter) Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-CmdLineParser.md Generates a command-line example string based on the provided filter, indicating which options should be included. ```APIDOC ## printExample(OptionHandlerFilter filter) ### Description Generates a command-line example string. ### Method ```java public String printExample(OptionHandlerFilter filter) ``` ### Parameters #### Path Parameters - **filter** (OptionHandlerFilter) - Controls which options are included in example ### Returns String like `-f FILE -v` with leading space, or empty string ### Example ```java String example = parser.printExample(OptionHandlerFilter.REQUIRED); System.err.println("java MyApp" + example + " "); ``` ``` -------------------------------- ### Configuration File Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/configuration-and-utilities.md Demonstrates how to use a configuration file (e.g., args.txt) with the '@' syntax to provide command-line arguments. This simplifies complex command lines. ```bash java MyApp @args.txt additional arguments here ``` -------------------------------- ### Custom Handler Option Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-Annotations.md Example of using a custom handler class for an option. ```java @Option(name="-b", handler=MyCustomHandler.class) private CustomType value; ``` -------------------------------- ### getDefaultMetaVariable Method Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-OptionHandler.md Example implementation returning 'FILE' as the default meta variable for usage display, indicating an expected file argument. ```java @Override public String getDefaultMetaVariable() { return "FILE"; // Usage shows: -f FILE } ``` -------------------------------- ### Custom Type Handler Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-OptionHandler.md Example demonstrating how to create and register a custom option handler for a user-defined type. ```APIDOC ## Creating Custom Handlers ### Example: Custom Type Handler ```java class MyTypeHandler extends OneArgumentOptionHandler { public MyTypeHandler(CmdLineParser parser, OptionDef option, Setter setter) { super(parser, option, setter); } @Override protected MyType parse(String arg) throws NumberFormatException, CmdLineException { try { return MyType.parse(arg); } catch (IllegalArgumentException e) { throw new CmdLineException(owner, "Invalid MyType: " + arg); } } @Override public String getDefaultMetaVariable() { return "MYTYPE"; } } // Register the handler OptionHandlerRegistry.getRegistry() .registerHandler(MyType.class, MyTypeHandler.class); // Now use with annotations @Option(name="-myopt") private MyType value; ``` ``` -------------------------------- ### Multi-valued Option Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-Annotations.md Example of a multi-valued option that can be specified multiple times to define properties. ```java @Option(name="-D", usage="define property") private List properties = new ArrayList<>(); ``` -------------------------------- ### Full Application Example with args4j Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/quick-reference.md A complete Java application demonstrating the use of `CmdLineParser` with required options, default values, multi-valued arguments, and error handling. ```java import org.kohsuke.args4j.*; import java.io.File; import java.util.ArrayList; import java.util.List; public class MyApp { @Option(name="-i", required=true, usage="input file") private File input; @Option(name="-o", usage="output file") private File output = new File("output.txt"); @Option(name="-v", usage="verbose") private boolean verbose = false; @Argument(index=0, multiValued=true, usage="additional files") private List files = new ArrayList<>(); public static void main(String[] args) { MyApp app = new MyApp(); CmdLineParser parser = new CmdLineParser(app); try { parser.parseArgument(args); app.run(); } catch (CmdLineException e) { System.err.println("Error: " + e.getMessage()); System.err.println("Usage: java MyApp [options] files..."); parser.printUsage(System.err); System.exit(1); } } private void run() { System.out.println("Input: " + input); System.out.println("Output: " + output); if (verbose) { System.out.println("Files: " + files); } } } ``` -------------------------------- ### Message Formatting Examples Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/configuration-and-utilities.md Shows how to format localized messages with parameters. Different messages accept varying numbers of arguments. ```java Messages.UNDEFINED_OPTION.format(optionName) Messages.ILLEGAL_OPERAND.format(optionName, value) Messages.REQUIRED_OPTION_MISSING.format(optionName) ``` -------------------------------- ### Option with Forbidding Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-Annotations.md Example of an option that conflicts with another option. ```java @Option(name="-verbose") private boolean verbose; @Option(name="-quiet", forbids={"-verbose"}, usage="quiet mode (conflicts with -verbose)") private boolean quiet; ``` -------------------------------- ### Boolean Option Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-Annotations.md Example of a simple boolean option for verbose output. ```java @Option(name="-v", usage="verbose output") private boolean verbose; ``` -------------------------------- ### CmdLineParser Initialization Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/architecture.md Illustrates the initialization flow of the CmdLineParser, starting from the user application code and progressing through ClassParser to identify and register options and arguments. ```text new CmdLineParser(bean, properties) ↓ ClassParser.parse(bean, parser) ↓ Scan bean.class hierarchy ↓ ├─ Find @Option fields/methods │ ↓ │ parser.addOption(setter, option) │ ↓ │ OptionHandlerRegistry creates OptionHandler │ ↓ │ options list │ └─ Find @Argument fields/methods ↓ parser.addArgument(setter, argument) ↓ OptionHandlerRegistry creates OptionHandler ↓ arguments list ``` -------------------------------- ### Data Flow Example for Simple Command Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/architecture.md Illustrates the step-by-step process of parsing a simple command line with options and arguments, showing how args4j processes tokens, invokes handlers, and updates bean state. ```text Input: ["-f", "input.txt", "process", "file1", "file2"] 1. CmdLineParser initialized ↓ ClassParser scans annotations ↓ Finds @Option(name="-f") private File inputFile Finds @Argument(index=0) private String action Finds @Argument(index=1, multiValued=true) private List files ↓ Creates OptionHandlers: - FileOptionHandler for inputFile - StringOptionHandler for action - StringOptionHandler for files (multi-valued) 2. parseArgument() called ↓ Token: "-f" ├─ Recognized as option ├─ Find handler: FileOptionHandler ├─ Call handler.parseArguments(params) │ ├─ Get parameter: "input.txt" │ ├─ Parse: new File("input.txt") │ ├─ Call setter.addValue(file) │ │ └─ field.set(bean, file) │ └─ Return 1 (consumed 1 arg) │ Token: "process" ├─ Not an option ├─ Use argument[0] handler: StringOptionHandler ├─ Call handler.parseArguments(params) │ ├─ Get parameter: "process" │ ├─ Parse: "process" (no conversion) │ ├─ Call setter.addValue("process") │ │ └─ field.set(bean, "process") │ └─ Return 1 │ Token: "file1" ├─ Not an option ├─ Use argument[1] handler: MultiValueFieldSetter ├─ Call handler.parseArguments(params) │ ├─ Get parameter: "file1" │ ├─ Parse: "file1" │ ├─ Call setter.addValue("file1") │ │ └─ list.add("file1") │ └─ Return 1 │ Token: "file2" ├─ Not an option ├─ Argument[1] is multiValued, handle again ├─ Call handler.parseArguments(params) │ ├─ Get parameter: "file2" │ ├─ Parse: "file2" │ ├─ Call setter.addValue("file2") │ │ └─ list.add("file2") │ └─ Return 1 3. Validation ├─ Check required options ├─ Check required arguments └─ Check dependencies/conflicts 4. Bean State ├─ inputFile = new File("input.txt") ├─ action = "process" └─ files = ["file1", "file2"] ``` -------------------------------- ### SubCommands Annotation Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-SubCommands.md Example of declaring multiple subcommands with names and aliases using the @SubCommands annotation. ```java @SubCommands(value = { @SubCommand(name = "commit"), @SubCommand(name = "push", aliases = {"pub"}), @SubCommand(name = "pull") }) private SubCommandHandler handler; ``` -------------------------------- ### Enum Option Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-Annotations.md Example of an enum option for logging level with a default value. ```java enum LogLevel { DEBUG, INFO, WARN, ERROR } @Option(name="-level", usage="logging level", metaVar="LEVEL") private LogLevel level = LogLevel.INFO; ``` -------------------------------- ### parseArguments Method Implementation Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-OptionHandler.md An example implementation for parsing String arguments. It adds the parsed token to the setter and returns the number of arguments consumed. ```java @Override public int parseArguments(Parameters params) throws CmdLineException { String token = params.getParameter(0); setter.addValue(token); return 1; // Consumed 1 argument } ``` -------------------------------- ### Usage Examples for Git-like CLI Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-SubCommands.md These bash commands illustrate how to invoke the Git-like CLI with different subcommands and options. They cover initialization, adding files, committing, pushing, and using verbose mode. ```bash # Init repository java GitCLI init ``` ```bash # Add files java GitCLI add file1.txt file2.txt ``` ```bash # Commit with message java GitCLI commit -m "initial commit" ``` ```bash # Push with upstream java GitCLI push -u ``` ```bash # Verbose mode java GitCLI -v commit -m "message" ``` ```bash # Amend with verbose java GitCLI -v commit --amend ``` -------------------------------- ### Custom Setter Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-Setters.md Demonstrates how to create and use a custom Setter implementation for special handling of option values, including validation and transformation. ```APIDOC ## Custom Setter ### Description Create custom setter for special handling. ### Example Implementation ```java public class CustomSetter implements Setter { private final Object bean; private final Field field; public CustomSetter(Object bean, Field field) { this.bean = bean; this.field = field; } @Override public void addValue(String value) throws CmdLineException { try { // Custom validation or transformation String validated = validate(value); field.set(bean, validated); } catch (IllegalAccessException e) { throw new CmdLineException(null, "Cannot set field: " + e.getMessage()); } } @Override public Class getType() { return String.class; } @Override public boolean isMultiValued() { return false; } @Override public FieldSetter asFieldSetter() { return new FieldSetter(bean, field); } @Override public AnnotatedElement asAnnotatedElement() { return field; } private String validate(String value) throws CmdLineException { if (value == null || value.isEmpty()) { throw new CmdLineException(null, "Value cannot be empty"); } return value.toLowerCase(); } } // Use with programmatic option registration: public static void main(String[] args) throws Exception { MyClass bean = new MyClass(); Field field = MyClass.class.getDeclaredField("option"); CmdLineParser parser = new CmdLineParser(null); Setter setter = new CustomSetter(bean, field); Option opt = ...; // Create option annotation parser.addOption(setter, opt); parser.parseArgument(args); } ``` ``` -------------------------------- ### String Option with Alias and Metadata Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-Annotations.md Example of a string option with an alias, usage text, metadata variable, and marked as required. ```java @Option(name="-f", aliases={"--file"}, usage="input file", metaVar="FILE", required=true) private String filename; ``` -------------------------------- ### Example of Using SubCommand Annotation Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/types.md Demonstrates how to use the @SubCommand annotation with @SubCommands to define and configure a subcommand handler for parsing git-like commands. ```java // java app commit -m "message" // java app push -remote origin @SubCommands(value={ @SubCommand(name="commit"), @SubCommand(name="push") }) private SubCommandHandler handler; ``` -------------------------------- ### Localizable Interface Usage Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/configuration-and-utilities.md Demonstrates how to use the Localizable interface to format messages. Includes examples for formatting with the default locale and a specific locale. ```java // Format with default locale String msg = message.format("param1", "param2"); // Format with specific locale String msg = message.formatWithLocale(Locale.FRENCH, "param1"); ``` -------------------------------- ### Subcommand Parsing Usage Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-SubCommands.md Example of parsing arguments for subcommands like 'commit' and 'push' using CmdLineParser. ```java GitOptions opts = new GitOptions(); CmdLineParser parser = new CmdLineParser(opts); parser.parseArgument("commit", "-m", "initial commit"); // Parses "commit" as subcommand, then "-m" as option to commit parser.parseArgument("push", "-f"); // Parses "push" as subcommand, then "-f" as option to push ``` -------------------------------- ### Get Options Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-CmdLineParser.md Retrieves a list of all registered option handlers. This is useful for inspecting option configurations. ```java public List getOptions() ``` -------------------------------- ### Create Default ParserProperties Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-ParserProperties.md Initializes a new ParserProperties instance with default settings. This is the starting point for chaining configuration methods. ```java public static ParserProperties defaults() ``` -------------------------------- ### Configure Parser Properties Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/quick-reference.md Customize parser behavior using ParserProperties. This example sets the usage width, enables '@' syntax for file expansion, and shows default values in usage. ```java // Create parser with configuration ParserProperties props = ParserProperties.defaults() .withUsageWidth(120) .withAtSyntax(true) .withShowDefaults(true); CmdLineParser parser = new CmdLineParser(bean, props); ``` -------------------------------- ### Custom Setter Implementation Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-Setters.md Provides an example of creating a custom Setter implementation for specialized validation or transformation of input values before setting them to a field. ```java public class CustomSetter implements Setter { private final Object bean; private final Field field; public CustomSetter(Object bean, Field field) { this.bean = bean; this.field = field; } @Override public void addValue(String value) throws CmdLineException { try { // Custom validation or transformation String validated = validate(value); field.set(bean, validated); } catch (IllegalAccessException e) { throw new CmdLineException(null, "Cannot set field: " + e.getMessage()); } } @Override public Class getType() { return String.class; } @Override public boolean isMultiValued() { return false; } @Override public FieldSetter asFieldSetter() { return new FieldSetter(bean, field); } @Override public AnnotatedElement asAnnotatedElement() { return field; } private String validate(String value) throws CmdLineException { if (value == null || value.isEmpty()) { throw new CmdLineException(null, "Value cannot be empty"); } return value.toLowerCase(); } } // Use with programmatic option registration: public static void main(String[] args) throws Exception { MyClass bean = new MyClass(); Field field = MyClass.class.getDeclaredField("option"); CmdLineParser parser = new CmdLineParser(null); Setter setter = new CustomSetter(bean, field); Option opt = ...; // Create option annotation parser.addOption(setter, opt); parser.parseArgument(args); } ``` -------------------------------- ### ArrayFieldSetter Usage Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-Setters.md Shows how multiple occurrences of an option with an array field result in the field being populated with multiple values. ```java @Option(name = "-files") private File[] files; // Multiple occurrences: // -files a.txt -files b.txt // Results in: files = [new File("a.txt"), new File("b.txt")] ``` -------------------------------- ### MultiValueFieldSetter Usage Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-Setters.md Illustrates how multiple option occurrences are added to a List field using MultiValueFieldSetter. ```java @Option(name = "-files") private List files = new ArrayList<>(); // Multiple occurrences: // -files a.txt -files b.txt // Results in: files = [new File("a.txt"), new File("b.txt")] ``` -------------------------------- ### FieldSetter addValue Method Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-Setters.md Demonstrates how the addValue method in FieldSetter updates the target field with the parsed value. ```java public void addValue(Object value) ``` ```java @Option(name = "-count") private int count; // When parsing "-count 42": // setter.addValue(42) // Results in: this.count = 42 ``` -------------------------------- ### NamedOptionDef Example Usage Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/types.md Illustrates how a NamedOptionDef object would represent an @Option annotation with aliases and dependencies. This shows the mapping from annotation attributes to NamedOptionDef methods. ```java @Option(name="-file", aliases={"--filename"}, depends={"-mode"}) private String filename; // NamedOptionDef will have: // name() = "-file" // aliases() = ["--filename"] // depends() = ["-mode"] ``` -------------------------------- ### ParserProperties.withAtSyntax(boolean atSyntax) Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-ParserProperties.md Enables or disables the @-file syntax, which allows arguments starting with '@' to be treated as file paths whose contents are parsed as arguments. ```APIDOC ## ParserProperties.withAtSyntax(boolean atSyntax) ### Description Enables/disables @-file syntax. When enabled, arguments starting with @ are treated as file paths. The file contents are read and each line is treated as an argument. ### Method ```java public ParserProperties withAtSyntax(boolean atSyntax) ``` ### Parameters #### Path Parameters - **atSyntax** (boolean) - Required - true to enable, false to disable ### Returns this (for chaining) ### Default true ### Example ```java // args.txt contains: // -f input.txt // -o output.txt // -v // With at-syntax enabled: parser.parseArgument("@args.txt"); // Expands to: -f input.txt -o output.txt -v // With at-syntax disabled: props.withAtSyntax(false); parser.parseArgument("@args.txt"); // Treats literally as argument "@args.txt" ``` ``` -------------------------------- ### getParameter(int idx) Method Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-OptionHandler.md Gets a parameter relative to the current position. Used to retrieve specific command-line arguments during parsing. ```java String getParameter(int idx) throws CmdLineException ``` ```java // Command: "-file foo.txt -other" // In parseArguments() for -file: String filename = params.getParameter(0); // "foo.txt" ``` -------------------------------- ### Handling Non-sequential Argument Indices Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/errors.md This example illustrates an IllegalAnnotationError or NullPointerException that can occur with non-sequential argument indices. Argument indices should be sequential starting from 0. ```java // ERROR: Non-sequential argument indices @Argument(index=0) private String arg1; @Argument(index=2) private String arg2; // Missing index 1! new CmdLineParser(bean); // May throw error or cause NPE during parsing ``` -------------------------------- ### Run Business Logic with Starter Class Source: https://github.com/kohsuke/args4j/wiki/Home Command to run the Business class using the Args4j Starter class without any arguments. This demonstrates the default behavior when no command-line options are provided. ```bash java -classpath .;args4j-2.32.jar -Dmainclass=Business org.kohsuke.args4j.Starter ``` -------------------------------- ### Add Args4j Annotations to Business Class Source: https://github.com/kohsuke/args4j/wiki/Home Java code snippet showing how to add Args4j annotations (@Option) to class fields and setter methods for command-line argument parsing. This example adds annotations for 'name' and 'file'. ```java import org.kohsuke.args4j.Option; ... @Option(name="-name",usage="Sets a name") public String name; ... @Option(name="-file",usage="Sets a file if that is present") public void setFile(File f) { ... ``` -------------------------------- ### IntOptionHandler Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-OptionHandlers.md Parses 32-bit integer values. It handles types `int` and `Integer`, uses 'N' as the meta variable, and throws `CmdLineException` for non-integer input. Example values include -1, 0, and 2147483647. ```APIDOC ## IntOptionHandler ### Description Parses integer (32-bit) values. ### Type `int`, `Integer` ### Meta variable `N` ### Throws `CmdLineException` on non-integer input ### Example values - `-1` - `0` - `2147483647` ### Usage Example ```java @Option(name="-count") private int count; parser.parseArgument("-count", "42"); // count = 42 ``` ``` -------------------------------- ### Run Business Logic with Arguments Source: https://github.com/kohsuke/args4j/wiki/Home Command to run the Business class using the Args4j Starter class with '-name' and '-file' arguments. This demonstrates basic argument parsing. ```bash java -classpath .;args4j-2.32.jar -Dmainclass=Business org.kohsuke.args4j.Starter -name "Hrld" -file args4j-2.32.jar ``` -------------------------------- ### Equivalent Command Line Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/configuration-and-utilities.md Shows the expanded equivalent of the command line using a configuration file. Each argument from the file is listed as if it were directly on the command line. ```bash java MyApp \ -input data.csv \ -output results.csv \ -mode production \ -threads 8 \ -verbose \ -log /var/log/app.log \ -experimental-feature1 \ -experimental-feature2 \ additional arguments here ``` -------------------------------- ### Configure ParserProperties with Defaults Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-ParserProperties.md Demonstrates creating default properties and chaining methods to customize usage width and @-file syntax. Used to configure a CmdLineParser instance. ```java ParserProperties props = ParserProperties.defaults() .withUsageWidth(100) .withAtSyntax(false); CmdLineParser parser = new CmdLineParser(bean, props); ``` -------------------------------- ### Custom Type Handler Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-OptionHandler.md Example of creating a custom handler for a type by extending OneArgumentOptionHandler. This handler parses a String argument into a custom MyType object. ```java class MyTypeHandler extends OneArgumentOptionHandler { public MyTypeHandler(CmdLineParser parser, OptionDef option, Setter setter) { super(parser, option, setter); } @Override protected MyType parse(String arg) throws NumberFormatException, CmdLineException { try { return MyType.parse(arg); } catch (IllegalArgumentException e) { throw new CmdLineException(owner, "Invalid MyType: " + arg); } } @Override public String getDefaultMetaVariable() { return "MYTYPE"; } } // Register the handler OptionHandlerRegistry.getRegistry() .registerHandler(MyType.class, MyTypeHandler.class); // Now use with annotations @Option(name="-myopt") private MyType value; ``` -------------------------------- ### Configuration File with @-Syntax Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/patterns-and-examples.md Use the @-syntax to load arguments from a configuration file. Each line in the file is treated as a separate command-line argument. ```java public class ConfigApp { @Option(name = "-f", metaVar = "FILE") private File configFile; @Option(name = "-mode") private String mode = "default"; public static void main(String[] args) throws CmdLineException { ConfigApp app = new ConfigApp(); CmdLineParser parser = new CmdLineParser(app); // @args.txt expands to contents of args.txt (one arg per line) parser.parseArgument(args); System.out.println("Mode: " + app.mode); } } ``` ```text -f /path/to/config.yaml -mode production ``` ```bash java ConfigApp @args.txt # Equivalent to: java ConfigApp -f /path/to/config.yaml -mode production ``` -------------------------------- ### getValueList() Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-OptionHandler.md Gets the current value(s) of the property. ```APIDOC ## getValueList() ### Description Gets the current value(s) of the property. ### Returns List with current values, empty list, or null if no current value ``` -------------------------------- ### args4j Documentation Structure Overview Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/README.md This diagram illustrates the organization of the args4j documentation, showing the main entry points and how different sections relate to each other. It helps users understand where to find specific information. ```text Start: quick-reference.md ├─ [patterns-and-examples.md] - See real usage ├─ [architecture.md] - Understand how it works │ ├─ API Reference (pick as needed) │ ├─ [api-reference-CmdLineParser.md] │ ├─ [api-reference-Annotations.md] │ ├─ [api-reference-OptionHandler.md] │ ├─ [api-reference-OptionHandlers.md] │ ├─ [api-reference-Setters.md] │ ├─ [api-reference-ParserProperties.md] │ ├─ [api-reference-SubCommands.md] │ ├─ Reference │ ├─ [types.md] - Type definitions │ ├─ [errors.md] - Exception reference │ ├─ [configuration-and-utilities.md] │ └─ [architecture.md] - Deep dive into design ``` -------------------------------- ### Basic Annotation Usage with Args4j Source: https://github.com/kohsuke/args4j/blob/master/args4j/src/org/kohsuke/args4j/package.html Demonstrates the typical use of Args4j by defining a bean class with an @Option annotation and parsing arguments in the main method. ```java public class Bean { @Option(name="-text") String text; } public class Main { public static void main(String[] args) throws CmdLineException { Object bean = new Bean(); CmdLineParser parser = new CmdLineParser(bean); parser.parse(args); } } ``` -------------------------------- ### getParameter(int idx) Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-OptionHandler.md Gets a parameter relative to the current position. ```APIDOC ## getParameter(int idx) ### Description Gets a parameter relative to the current position. ### Parameters #### Path Parameters - **idx** (int) - Required - Index (0 = next token, 1 = token after that) ### Returns The token at that position ### Throws `CmdLineException` - if index is out of bounds ### Example ```java // Command: "-file foo.txt -other" // In parseArguments() for -file: String filename = params.getParameter(0); // "foo.txt" ``` ``` -------------------------------- ### Git-like CLI with Subcommands Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-SubCommands.md This Java code demonstrates how to create a Git-like command-line interface using args4j's SubCommand and SubCommandHandler features. It defines global options, subcommand-specific options, and handles parsing and execution for various Git commands. ```java import org.kohsuke.args4j.*; import org.kohsuke.args4j.spi.SubCommand; import org.kohsuke.args4j.spi.SubCommandHandler; import org.kohsuke.args4j.spi.SubCommands; import java.util.ArrayList; import java.util.List; public class GitCLI { @SubCommands(value = { @SubCommand(name = "init"), @SubCommand(name = "add"), @SubCommand(name = "commit"), @SubCommand(name = "push", aliases = {"pub"}), @SubCommand(name = "pull"), @SubCommand(name = "log") }) private SubCommandHandler handler; // Global options @Option(name = "-v", usage = "verbose output") private boolean verbose = false; @Option(name = "-C", usage = "run in directory", metaVar = "DIR") private String directory = "."; // Subcommand: add @Option(name = "-A", usage = "add all (for 'add' subcommand)") private boolean addAll = false; // Subcommand: commit @Option(name = "-m", usage = "commit message") private String message; @Option(name = "--amend", usage = "amend previous commit") private boolean amend = false; // Subcommand: push/pull @Option(name = "-u", usage = "set upstream") private boolean setUpstream = false; @Option(name = "-f", usage = "force") private boolean force = false; // File arguments for 'add' @Argument(index = 0) private List files = new ArrayList<>(); public static void main(String[] args) throws CmdLineException { GitCLI cli = new GitCLI(); CmdLineParser parser = new CmdLineParser(cli); try { parser.parseArgument(args); cli.run(); } catch (CmdLineException e) { System.err.println("Error: " + e.getMessage()); System.err.println("Usage: git [options] [command-options]"); parser.printUsage(System.err); System.exit(1); } } private void run() { if (verbose) { System.out.println("Running in: " + directory); } switch (handler) { case "init": doInit(); break; case "add": doAdd(); break; case "commit": doCommit(); break; case "push": case "pub": doPush(); break; case "pull": doPull(); break; case "log": doLog(); break; } } private void doInit() { System.out.println("Initializing repository..."); } private void doAdd() { System.out.println("Adding files: " + files); if (addAll) System.out.println("(all files)"); } private void doCommit() { System.out.println("Committing with message: " + message); if (amend) System.out.println("Amending previous commit"); } private void doPush() { System.out.println("Pushing changes"); if (setUpstream) System.out.println("Setting upstream"); if (force) System.out.println("Force pushing"); } private void doPull() { System.out.println("Pulling changes"); } private void doLog() { System.out.println("Showing commit log"); } } ``` -------------------------------- ### Business Logic Implementation Source: https://github.com/kohsuke/args4j/wiki/Home A simple Java class demonstrating business logic with fields for name and file. It includes a setter for the file and a run method to print the business logic details. ```java import java.io.File; public class Business { public String name; public File file; public void setFile(File f) { if (f.exists()) file = f; } public void run() { System.out.println("Business-Logic"); System.out.println("- name: " + name); System.out.println("- file: " + ((file!=null) ? file.getAbsolutePath() : "null")); } } ``` -------------------------------- ### Get Option Sorter Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-ParserProperties.md Retrieves the comparator used for sorting options. Returns null if no sorting is applied. ```java Comparator getOptionSorter() ``` -------------------------------- ### Help Option Configuration Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/quick-reference.md Implement a help option that, when present, skips validation of other required options. Set `help=true` for the option. ```java @Option(name="-h", help=true) private boolean help; // When -h is set, required option validation is skipped ``` -------------------------------- ### Get Arguments Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-CmdLineParser.md Retrieves a list of all registered argument handlers in the order they were registered. This is useful for inspecting argument configurations. ```java public List getArguments() ``` -------------------------------- ### Custom Help Option Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/patterns-and-examples.md Implement a custom help option to display usage information and available options. This is useful for providing user-friendly command-line interfaces. ```java public class MyApp { @Option(name = "-h", aliases = {"--help"}, help = true, usage = "show help") private boolean help = false; @Option(name = "-config") private File configFile; public static void main(String[] args) { MyApp app = new MyApp(); CmdLineParser parser = new CmdLineParser(app); try { parser.parseArgument(args); if (app.help) { System.out.println("Usage: java MyApp [options]"); parser.printUsage(System.out); return; } app.run(); } catch (CmdLineException e) { System.err.println("Error: " + e.getMessage()); System.err.println("Use -h or --help for usage"); System.exit(1); } } private void run() { System.out.println("Running..."); } } ``` -------------------------------- ### Print All Options Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/configuration-and-utilities.md Prints all options, including hidden ones, to the specified output stream. Useful for debugging or comprehensive documentation. ```java parser.printUsage(System.err, null, OptionHandlerFilter.ALL); ``` -------------------------------- ### Handling Annotation on Final Field Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/errors.md This example demonstrates an IllegalAnnotationError when an annotation is applied to a final field. Annotations should not be used on final fields. ```java // ERROR: Annotation on final field @Option(name="-x") private final String constant = "value"; // IllegalAnnotationError! new CmdLineParser(bean); // Throws IllegalAnnotationError ``` -------------------------------- ### getValueList() Method Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-OptionHandler.md Gets the current value(s) of the property. Returns a list with current values, an empty list, or null if no current value. ```java List getValueList() ``` -------------------------------- ### Programmatic Option Registration Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/patterns-and-examples.md Shows how to dynamically register options at runtime using reflection. This is an advanced technique typically not required for standard option parsing. ```java public class DynamicApp { private Map options = new HashMap<>(); public void addOption(String name, String value) { options.put(name, value); } public static void main(String[] args) throws Exception { DynamicApp app = new DynamicApp(); CmdLineParser parser = new CmdLineParser(app); // Programmatically add options at runtime Field optionsField = DynamicApp.class.getDeclaredField("options"); Setter setter = Setters.create(optionsField, app); // Create option dynamically // (Note: this is advanced usage, typically not needed) parser.parseArgument(args); System.out.println("Options: " + app.options); } } ``` -------------------------------- ### ParserProperties.defaults() Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-ParserProperties.md Creates a new ParserProperties instance with default settings. These defaults include a usage width of 80 columns, enabled at-syntax for file arguments, enabled display of default values, space as the option value delimiter, and alphabetical sorting of options. ```APIDOC ## ParserProperties.defaults() ### Description Creates a new ParserProperties instance with default settings. ### Method ```java public static ParserProperties defaults() ``` ### Returns New ParserProperties with: - Usage width: 80 columns - At-syntax enabled (@file support) - Default values shown: enabled - Option value delimiter: space - Option sorting: alphabetical ### Example ```java ParserProperties props = ParserProperties.defaults() .withUsageWidth(100) .withAtSyntax(false); CmdLineParser parser = new CmdLineParser(bean, props); ``` ``` -------------------------------- ### MethodSetter addValue Example Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-Setters.md Demonstrates how the addValue method of MethodSetter is used to invoke a method with a parsed value. This is typically called internally by the parser. ```java @Option(name = "-count") public void setCount(int value) { this.count = value; } // When parsing "-count 42": // setter.addValue(42) // Results in: setCount(42) ``` -------------------------------- ### Localize Option Help Messages using ResourceBundle Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/configuration-and-utilities.md Demonstrates how to localize option help messages using ResourceBundle. This involves defining help strings in properties files and loading them based on the user's locale. ```java public class LocalizedApp { @Option(name = "-f", usage = "option.input.help") private File input; @Option(name = "-o", usage = "option.output.help") private File output; public static void main(String[] args) throws CmdLineException { LocalizedApp app = new LocalizedApp(); CmdLineParser parser = new CmdLineParser(app); // Load messages for user's locale ResourceBundle messages = ResourceBundle.getBundle("messages"); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getLocalizedMessage()); parser.printUsage(System.err, messages); // Localized usage System.exit(1); } } } ``` ```properties option.input.help=Input file path option.output.help=Output file path ``` ```properties option.input.help=Chemin du fichier d'entrée option.output.help=Chemin du fichier de sortie ``` -------------------------------- ### Compile Business Logic Source: https://github.com/kohsuke/args4j/wiki/Home Command to compile the Business.java file, including the necessary args4j jar in the classpath. Assumes args4j-2.32.jar is in the current directory. ```bash javac -classpath .;args4j-2.32.jar Business.java ``` -------------------------------- ### Handling Duplicate Option Names Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/errors.md This example shows an IllegalAnnotationError being thrown due to duplicate option names. Ensure each option name is unique. ```java // ERROR: Duplicate option names @Option(name="-f") private String file1; @Option(name="-f") private String file2; // IllegalAnnotationError! new CmdLineParser(bean); // Throws IllegalAnnotationError ``` -------------------------------- ### getOptions Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-CmdLineParser.md Retrieves all registered option handlers. ```APIDOC ## getOptions() ### Description Returns all registered option handlers. ### Method `getOptions` ### Parameters None ### Returns List of OptionHandler objects for @Option-annotated fields ``` -------------------------------- ### Get Properties Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-CmdLineParser.md Returns the current ParserProperties instance, which holds the parser's configuration settings. This allows inspection or modification of parser behavior. ```java public ParserProperties getProperties() ``` -------------------------------- ### Custom Setter Registration Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/architecture.md Demonstrates how to create a custom Setter implementation and use it during programmatic registration with the parser. ```java public class CustomSetter implements Setter { @Override public void addValue(String value) throws CmdLineException { ... } // ... other methods } // Use in programmatic registration parser.addOption(new CustomSetter(...), option); ``` -------------------------------- ### Custom Option Filter Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/configuration-and-utilities.md Applies a custom filter to determine which options are displayed in the usage message. This example shows how to display non-hidden and required options. ```java OptionHandlerFilter custom = o -> !o.option.hidden() && o.option.required(); parser.printUsage(System.err, null, custom); ``` -------------------------------- ### Basic Argument Parsing with Options and Arguments Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/patterns-and-examples.md Parses simple options like input/output files and a verbose flag, along with required and optional arguments for processing mode and additional files. Use this for standard command-line applications. ```java import org.kohsuke.args4j.*; import java.io.File; import java.util.ArrayList; import java.util.List; public class FileProcessor { @Option(name = "-i", aliases = {"--input"}, usage = "input file", required = true, metaVar = "FILE") private File inputFile; @Option(name = "-o", aliases = {"--output"}, usage = "output file", required = true, metaVar = "FILE") private File outputFile; @Option(name = "-v", usage = "verbose output") private boolean verbose = false; @Argument(index = 0, usage = "processing mode", metaVar = "MODE", required = true) private String mode; @Argument(index = 1, multiValued = true, usage = "additional files") private List additionalFiles = new ArrayList<>(); public static void main(String[] args) { FileProcessor processor = new FileProcessor(); CmdLineParser parser = new CmdLineParser(processor); try { parser.parseArgument(args); processor.process(); } catch (CmdLineException e) { System.err.println("Error: " + e.getMessage()); System.err.println("Usage: java FileProcessor [options] [files...]"); parser.printUsage(System.err); System.exit(1); } } private void process() { System.out.println("Processing: " + mode); System.out.println("Input: " + inputFile); System.out.println("Output: " + outputFile); if (verbose) { System.out.println("Verbose mode enabled"); if (!additionalFiles.isEmpty()) { System.out.println("Additional files: " + additionalFiles); } } } } ``` ```bash java FileProcessor -i input.txt -o output.txt transform java FileProcessor --input data.csv --output result.csv convert file1 file2 java FileProcessor -i in.txt -o out.txt -v process ``` -------------------------------- ### OptionHandlerFilter Interface Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/types.md An interface used to select which OptionHandler objects should be included in outputs like usage or examples. Implementations can filter based on various criteria. ```APIDOC ## OptionHandlerFilter Interface Selects which OptionHandler objects to include in output (usage, examples). ### Constants | Name | Description | |------|-------------| | ALL | Includes all OptionHandlers. | | PUBLIC | Includes only OptionHandlers that are not hidden. | | REQUIRED | Includes only OptionHandlers that are marked as required. | ``` -------------------------------- ### getNameAndMeta Method Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-OptionHandler.md Formats the option name and meta variable for usage strings, like '-f FILE'. Supports localization and parser property configurations. ```java public final String getNameAndMeta(ResourceBundle rb, ParserProperties properties) ``` -------------------------------- ### Configure Parser Properties with Fluent API Source: https://github.com/kohsuke/args4j/blob/master/_autodocs/api-reference-ParserProperties.md Demonstrates using the fluent API to set various properties for a CmdLineParser. This includes setting the usage width, enabling/disabling the '@' syntax for file arguments, controlling the display of default values, and specifying the delimiter for option values. ```java ParserProperties props = ParserProperties.defaults() .withUsageWidth(120) .withAtSyntax(true) .withShowDefaults(true) .withOptionValueDelimiter("="); CmdLineParser parser = new CmdLineParser(optionsBean, props); ```