Lanat Help

Instantiating the command template

By using the terminator into(Class) method in the AfterParseOptions class, you can instantiate a command template class and set all the fields annotated with @Argument.Define with the parsed values given by the parse result.

Tutorial

  1. Let's assume we have a command template class like this:

    @Command.Define public class MyProgram extends CommandTemplate { @Argument.Define public double a; @Argument.Define public double b; }
  2. Then, after parsing the arguments, call the into method with the class of the command template:

    public static void main(String[] args) { var result = ArgumentParser.from(MyProgram.class) .parse(CLInput.from(args)) .into(MyProgram.class); }
  3. MyProgram will be instantiated and returned with the fields a and b set to the parsed values:

    System.out.printf("a: %f, b: %f", result.a, result.b);

Instantiating sub-commands as well

If the command template class has sub-commands defined, the into method will also instantiate them recursively if properly defined:

Tutorial

  1. Let's assume we have a command template class with a sub-command like this:

    @Command.Define public class MyProgram extends CommandTemplate { @Argument.Define public double a; @Command.Define public class SubCommand extends CommandTemplate { @Argument.Define public double b; } }
  2. In order to be able to access the sub-command instance upon instantiation, you need to define a @CommandAccesor property:

    @Command.Define public class MyProgram extends CommandTemplate { ... @CommandAccessor public SubCommand subCmd; ... }
  3. Now, after parsing the arguments, call the into method with the class of the command template, and access the sub-command's fields:

    public static void main(String[] args) { var result = ArgumentParser.from(MyProgram.class) .parse(CLInput.from(args)) .into(MyProgram.class); System.out.printf("a: %f, b: %f", result.a, result.subCmd.b); }

@Argument.Define field type requirements

When using the into method, the fields annotated with @Argument.Define must have a valid type for the value that has been parsed. If the type of the field is not compatible with the parsed value, an IncompatibleCommandTemplateTypeException will be thrown.

Here are a few recommendations for the types of the fields:

  • Only use primitive types for arguments that you know will always return a non-null value, such as required arguments, for example.

  • Make sure the field type is compatible with what the argument type will return. For example, if the argument is a StringArgumentType, the field should be a String.

  • Wrap the field type in an Optional if you wish to use a Optional.empty() instead of null when no value is provided. Read more.

Last modified: 30 April 2024