Class CommandLineArgumentParser

java.lang.Object
nl.colorize.util.cli.CommandLineArgumentParser

public class CommandLineArgumentParser extends Object
Define supported arguments for a command line interface, then parse the provided arguments accordingly. This class only allows named arguments and flags, arguments without an explicit name are not supported.

Refer to the library's README file for information and examples on how to define a command line interface using this class.

When providing argument values on the command line, argument names are considered case-insensitive and normalized. For example, using "input", "-input", "--input", or "--input=value" all map to the same argument.

This class exists because Args4j has not been updated since 2016. Command line arguments are defined using annotations, in a similar way to Args4j. However, the annotations are added to record fields, which Args4j couldn't use because it predates records being introduced in Java 17.

  • Constructor Details

    • CommandLineArgumentParser

      public CommandLineArgumentParser(String applicationName)
    • CommandLineArgumentParser

      public CommandLineArgumentParser(Class<?> applicationName)
    • CommandLineArgumentParser

      protected CommandLineArgumentParser(String applicationName, PrintWriter out, boolean exitOnFail)
  • Method Details

    • getPropertyDeserializer

      public PropertyDeserializer getPropertyDeserializer()
      Returns the PropertyDeserializer that is used to convert command line arguments, which are always strings, to the correct type.
    • addDescription

      public void addDescription(String... lines)
      Extends the usage description with the specified line. This information will be displayed when the command line interface's usage information messsage is printed.
    • disableColor

      public void disableColor()
      By default, command line output uses ANSI color to improve readability. Calling this method disables colors and reverts to plain text output.
    • printUsage

      public void printUsage(Class<?> cli)
      Prints the usage information message for the command line interface. This is done automatically if the provides arguments are incomplete.
    • parse

      public <T> T parse(String[] argv, Class<T> cli) throws CommandLineInterfaceException
      Parses the command line arguments based on the Arg annotations in the specified class. If the provided arguments are incomplete or invalid, usage information will be displayed. If this class was configured to exit on failure, System.exit will be invoked to exit the application.
      Throws:
      CommandLineInterfaceException - If the provided arguments are incomplete or invalid.
      IllegalArgumentException - if cli does not define any constructor arguments annotated withArg.