Package com.beust.jcommander
Class JCommander
java.lang.Object
com.beust.jcommander.JCommander
The main class for JCommander. It's responsible for parsing the object that contains
all the annotated fields, parse the command line and assign the fields with the correct
values and a few other helper methods, such as usage().
The object(s) you pass in the constructor are expected to have one or more
\@Parameter annotations on them. You can pass either a single object, an array of objects
or an instance of Iterable. In the case of an array or Iterable, JCommander will collect
the \@Parameter annotations from all the objects passed in parameter.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classprivate class(package private) static classDescription of a main parameter, which can be either a list of string or a single field.private static classOptions shared with sub commandsstatic final classEncapsulation of either a main application or an individual command. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate Map<FuzzyMap.IKey,JCommander.ProgramName> Alias database for reverse lookupprivate Map<JCommander.ProgramName,JCommander> List of commands and their instance.private Consolestatic final Stringprivate final IVariableArityprivate Map<FuzzyMap.IKey,ParameterDescription> A map to look up parameter description per option name.private Map<Parameterized,ParameterDescription> A map of all the parameterized fields/methods.private booleanprivate JCommander.MainParameterThe objects that contain fields annotated with @Parameter.private final JCommander.Optionsprivate StringThe name of command or alias as it was passed to the command lineprivate StringThe name of the command after the parsing has run.private JCommander.ProgramNameprivate Map<Parameterized,ParameterDescription> A set of all the parameterizeds that are required.private IUsageFormatterThe usage formatter to use inusage(). -
Constructor Summary
ConstructorsModifierConstructorDescriptionCreates a new un-configured JCommander object.privateJCommander(JCommander.Options options) JCommander(Object object) JCommander(Object object, String... args) Deprecated.Construct a JCommander instance first and then call parse() on it.JCommander(Object object, ResourceBundle bundle) JCommander(Object object, ResourceBundle bundle, String... args) -
Method Summary
Modifier and TypeMethodDescriptionvoidaddCommand(Object object) voidaddCommand(String name, Object object) Add a command object.voidaddCommand(String name, Object object, String... aliases) Add a command object and its aliases.voidaddConverterFactory(IStringConverterFactory converterFactory) Adds a factory to lookup string converters.voidaddConverterInstanceFactory(IStringConverterInstanceFactory converterInstanceFactory) Adds a factory to lookup string converters.private voidaddDescription(Object object) final voidAdds the provided arg object to the set of objects that this commander will parse arguments into.convertValue(Parameterized parameterized, Class type, String optionName, String value) voidCreate the ParameterDescriptions for all the \@Parameter found.private final intdetermineArity(String[] args, int index, ParameterDescription pd, IVariableArity va) private String[]expandArgs(String[] originalArgv) Expand the command line parameters to take @ parameters into account.expandDynamicArg(String arg) private JCommanderfindCommandByAlias(String commandOrAlias) private IStringConverter<?>findConverterInstance(Parameter parameter, Class<?> forType, String optionName) private ParameterDescriptionprivate JCommander.ProgramNamefindProgramName(String name) intprivate ParameterDescriptiongetDescriptionFor(String arg) If arg is an option, we can look it up directly, but if it's a value, we need to find the description for the option that precedes it.Comparator<? super ParameterDescription>The name of the command or the alias in the form it was passed to the command line.private ParameterDescriptionGet the program display name (used only in the usage).Get the program name (used only in the usage).private StringgetSeparatorFor(String arg) Returns the usage formatter.private voidhandleBooleanOption(ParameterDescription pd, Class<?> fieldType) private voidprivate voidprivate voidInit the main parameter with the given arg.private static <T> TinstantiateConverter(String optionName, Class<? extends T> converterClass) private booleanisBooleanType(Class<?> fieldType) private booleanbooleanprivate booleanmatchArg(String arg, FuzzyMap.IKey key) static JCommander.Builderprivate voidprivate voidvoidParse and validate the command line parameters.private voidparseValues(String[] args, boolean validate) Main method that parses the values and initializes the fields accordingly.voidparseWithoutValidation(String... args) Parse the command line parameters without validating them.private static Stringprivate intprocessFixedArity(String[] args, int index, ParameterDescription pd, boolean validate, Class<?> fieldType) private intprocessFixedArity(String[] args, int originalIndex, ParameterDescription pd, boolean validate, Class<?> fieldType, int arity) private intprocessPassword(String[] args, int index, ParameterDescription pd, boolean validate) private intprocessVariableArity(String[] args, int index, ParameterDescription pd, boolean validate) Reads the file specified by filename and returns the file content as a string.private char[]readPassword(String description, boolean echoInput) Invoke Console.readPassword through reflection to avoid depending on Java 6.private Strings(int count) voidsetAcceptUnknownOptions(boolean b) voidsetAllowAbbreviatedOptions(boolean b) voidsetAllowParameterOverwriting(boolean b) voidsetAtFileCharset(Charset charset) Sets the charset used to expand@files.voidsetCaseSensitiveOptions(boolean b) voidsetColumnSize(int columnSize) voidsetConsole(Console console) voidsetDefaultProvider(IDefaultProvider defaultProvider) Define the default provider for this instance.final voidsetDescriptionsBundle(ResourceBundle bundle) Sets theResourceBundleto use for looking up descriptions.voidsetExpandAtSign(boolean expandAtSign) Disables expanding@file.voidvoidsetProgramName(String name) Set the program name (used only in the usage).voidsetProgramName(String name, String... aliases) Set the program namevoidsetUsageFormatter(IUsageFormatter usageFormatter) Sets the usage formatter.voidsetVerbose(int verbose) private String[]private static StringRemove spaces at both ends and handle double quotes.private static <T> TtryInstantiateConverter(String optionName, Class<T> converterClass) voidusage()Prints the usage ongetConsole()using the underlyingusageFormatter.private voidMake sure that all the required parameters have received a value.
-
Field Details
-
DEBUG_PROPERTY
- See Also:
-
descriptions
A map to look up parameter description per option name. -
objects
The objects that contain fields annotated with @Parameter. -
usageFormatter
The usage formatter to use inusage(). -
mainParameter
-
requiredFields
A set of all the parameterizeds that are required. During the reflection phase, this field receives all the fields that are annotated with required=true and during the parsing phase, all the fields that are assigned a value are removed from it. At the end of the parsing phase, if it's not empty, then some required fields did not receive a value and an exception is thrown. -
fields
A map of all the parameterized fields/methods. -
commands
List of commands and their instance. -
aliasMap
Alias database for reverse lookup -
parsedCommand
The name of the command after the parsing has run. -
parsedAlias
The name of command or alias as it was passed to the command line -
programName
-
helpWasSpecified
private boolean helpWasSpecified -
unknownArgs
-
console
-
options
-
DEFAULT_VARIABLE_ARITY
-
-
Constructor Details
-
JCommander
-
JCommander
public JCommander()Creates a new un-configured JCommander object. -
JCommander
- Parameters:
object- The arg object expected to containParameterannotations.
-
JCommander
- Parameters:
object- The arg object expected to containParameterannotations.bundle- The bundle to use for the descriptions. Can be null.
-
JCommander
- Parameters:
object- The arg object expected to containParameterannotations.bundle- The bundle to use for the descriptions. Can be null.args- The arguments to parse (optional).
-
JCommander
Deprecated.Construct a JCommander instance first and then call parse() on it.- Parameters:
object- The arg object expected to containParameterannotations.args- The arguments to parse (optional).
-
-
Method Details
-
setExpandAtSign
public void setExpandAtSign(boolean expandAtSign) Disables expanding@file. JCommander supports the@filesyntax, which allows you to put all your options into a file and pass this file as parameter @param expandAtSign whether to expand@file. -
setConsole
-
getConsole
- Returns:
- a wrapper for a
PrintStream, typicallySystem.out.
-
addObject
Adds the provided arg object to the set of objects that this commander will parse arguments into. -
setDescriptionsBundle
Sets theResourceBundleto use for looking up descriptions. Set this tonullto use description text directly. -
parse
Parse and validate the command line parameters. -
parseWithoutValidation
Parse the command line parameters without validating them. -
parse
-
initializeDefaultValues
private void initializeDefaultValues() -
validateOptions
private void validateOptions()Make sure that all the required parameters have received a value. -
pluralize
-
expandArgs
Expand the command line parameters to take @ parameters into account. When @ is encountered, the content of the file that follows is inserted in the command line.- Parameters:
originalArgv- the original command line parameters- Returns:
- the new and enriched command line parameters
-
expandDynamicArg
-
matchArg
-
isOption
-
getPrefixDescriptionFor
-
getDescriptionFor
If arg is an option, we can look it up directly, but if it's a value, we need to find the description for the option that precedes it. -
getSeparatorFor
-
readFile
Reads the file specified by filename and returns the file content as a string. End of lines are replaced by a space.- Parameters:
fileName- the command line filename- Returns:
- the file content as a string.
-
trim
Remove spaces at both ends and handle double quotes. -
createDescriptions
public void createDescriptions()Create the ParameterDescriptions for all the \@Parameter found. -
addDescription
-
initializeDefaultValue
-
parseValues
Main method that parses the values and initializes the fields accordingly. -
isBooleanType
-
handleBooleanOption
-
determineArity
private final int determineArity(String[] args, int index, ParameterDescription pd, IVariableArity va) -
processPassword
- Returns:
- the number of options that were processed.
-
processVariableArity
private int processVariableArity(String[] args, int index, ParameterDescription pd, boolean validate) - Returns:
- the number of options that were processed.
-
processFixedArity
private int processFixedArity(String[] args, int index, ParameterDescription pd, boolean validate, Class<?> fieldType) -
processFixedArity
private int processFixedArity(String[] args, int originalIndex, ParameterDescription pd, boolean validate, Class<?> fieldType, int arity) -
readPassword
Invoke Console.readPassword through reflection to avoid depending on Java 6. -
subArray
-
initMainParameterValue
Init the main parameter with the given arg. Note that the main parameter can be either a Listor a single value. -
getMainParameterDescription
-
setProgramName
Set the program name (used only in the usage). -
getProgramName
Get the program name (used only in the usage). -
getProgramDisplayName
Get the program display name (used only in the usage). -
setProgramName
Set the program name- Parameters:
name- program namealiases- aliases to the program name
-
usage
public void usage()Prints the usage ongetConsole()using the underlyingusageFormatter. -
setUsageFormatter
Sets the usage formatter.- Parameters:
usageFormatter- the usage formatter- Throws:
IllegalArgumentException- if the argument is null
-
getUsageFormatter
Returns the usage formatter.- Returns:
- the usage formatter
-
getOptions
-
getDescriptions
-
getMainParameter
-
newBuilder
-
getFields
-
getParameterDescriptionComparator
-
setParameterDescriptionComparator
-
setColumnSize
public void setColumnSize(int columnSize) -
getColumnSize
public int getColumnSize() -
getBundle
-
getParameters
- Returns:
- a Collection of all the \@Parameter annotations found on the target class. This can be used to display the usage() in a different format (e.g. HTML).
-
getMainParameterValue
- Returns:
- the main parameter description or null if none is defined.
-
p
-
setDefaultProvider
Define the default provider for this instance. -
addConverterFactory
Adds a factory to lookup string converters. The added factory is used prior to previously added factories.- Parameters:
converterFactory- the factory determining string converters
-
addConverterInstanceFactory
Adds a factory to lookup string converters. The added factory is used prior to previously added factories.- Parameters:
converterInstanceFactory- the factory generating string converter instances
-
findConverterInstance
private IStringConverter<?> findConverterInstance(Parameter parameter, Class<?> forType, String optionName) -
convertValue
public Object convertValue(Parameterized parameterized, Class type, String optionName, String value) - Parameters:
type- The type of the actual parameteroptionName-value- The value to convert
-
tryInstantiateConverter
-
instantiateConverter
private static <T> T instantiateConverter(String optionName, Class<? extends T> converterClass) throws InstantiationException, IllegalAccessException, InvocationTargetException -
addCommand
Add a command object. -
addCommand
-
addCommand
Add a command object and its aliases. -
getCommands
-
getRawCommands
-
getParsedCommand
-
getParsedAlias
The name of the command or the alias in the form it was passed to the command line.nullif no command or alias was specified.- Returns:
- Name of command or alias passed to command line. If none passed:
null.
-
s
- Returns:
- n spaces
-
getObjects
- Returns:
- the objects that JCommander will fill with the result of parsing the command line.
-
findParameterDescription
-
findCommand
-
findProgramName
-
findCommandByAlias
-
setVerbose
public void setVerbose(int verbose) -
setCaseSensitiveOptions
public void setCaseSensitiveOptions(boolean b) -
setAllowAbbreviatedOptions
public void setAllowAbbreviatedOptions(boolean b) -
setAcceptUnknownOptions
public void setAcceptUnknownOptions(boolean b) -
getUnknownOptions
-
setAllowParameterOverwriting
public void setAllowParameterOverwriting(boolean b) -
isParameterOverwritingAllowed
public boolean isParameterOverwritingAllowed() -
setAtFileCharset
Sets the charset used to expand@files.- Parameters:
charset- the charset
-