Package com.beust.jcommander
Class JCommander
- java.lang.Object
-
- com.beust.jcommander.JCommander
-
public class JCommander extends java.lang.ObjectThe 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 Classes Modifier and Type Class Description static classJCommander.Builderprivate classJCommander.DefaultVariableArity(package private) static classJCommander.MainParameterDescription of a main parameter, which can be either a list of string or a single field.private static classJCommander.OptionsOptions shared with sub commandsstatic classJCommander.ProgramNameEncapsulation of either a main application or an individual command.
-
Field Summary
Fields Modifier and Type Field Description private java.util.Map<FuzzyMap.IKey,JCommander.ProgramName>aliasMapAlias database for reverse lookupprivate java.util.Map<JCommander.ProgramName,JCommander>commandsList of commands and their instance.private Consoleconsolestatic java.lang.StringDEBUG_PROPERTYprivate IVariableArityDEFAULT_VARIABLE_ARITYprivate java.util.Map<FuzzyMap.IKey,ParameterDescription>descriptionsA map to look up parameter description per option name.private java.util.Map<Parameterized,ParameterDescription>fieldsA map of all the parameterized fields/methods.private booleanhelpWasSpecifiedprivate JCommander.MainParametermainParameterprivate java.util.List<java.lang.Object>objectsThe objects that contain fields annotated with @Parameter.private JCommander.Optionsoptionsprivate java.lang.StringparsedAliasThe name of command or alias as it was passed to the command lineprivate java.lang.StringparsedCommandThe name of the command after the parsing has run.private JCommander.ProgramNameprogramNameprivate java.util.Map<Parameterized,ParameterDescription>requiredFieldsA set of all the parameterizeds that are required.private java.util.List<java.lang.String>unknownArgsprivate IUsageFormatterusageFormatterThe usage formatter to use inusage().
-
Constructor Summary
Constructors Modifier Constructor Description JCommander()Creates a new un-configured JCommander object.privateJCommander(JCommander.Options options)JCommander(java.lang.Object object)JCommander(java.lang.Object object, java.lang.String... args)Deprecated.Construct a JCommander instance first and then call parse() on it.JCommander(java.lang.Object object, java.util.ResourceBundle bundle)JCommander(java.lang.Object object, java.util.ResourceBundle bundle, java.lang.String... args)
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidaddCommand(java.lang.Object object)voidaddCommand(java.lang.String name, java.lang.Object object)Add a command object.voidaddCommand(java.lang.String name, java.lang.Object object, java.lang.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(java.lang.Object object)voidaddObject(java.lang.Object object)Adds the provided arg object to the set of objects that this commander will parse arguments into.java.lang.ObjectconvertValue(Parameterized parameterized, java.lang.Class type, java.lang.String optionName, java.lang.String value)voidcreateDescriptions()Create the ParameterDescriptions for all the \@Parameter found.private intdetermineArity(java.lang.String[] args, int index, ParameterDescription pd, IVariableArity va)private java.lang.String[]expandArgs(java.lang.String[] originalArgv)Expand the command line parameters to take @ parameters into account.private java.util.List<java.lang.String>expandDynamicArg(java.lang.String arg)private JCommanderfindCommand(JCommander.ProgramName name)JCommanderfindCommandByAlias(java.lang.String commandOrAlias)private IStringConverter<?>findConverterInstance(Parameter parameter, java.lang.Class<?> forType, java.lang.String optionName)private ParameterDescriptionfindParameterDescription(java.lang.String arg)private JCommander.ProgramNamefindProgramName(java.lang.String name)java.util.ResourceBundlegetBundle()intgetColumnSize()java.util.Map<java.lang.String,JCommander>getCommands()ConsolegetConsole()private ParameterDescriptiongetDescriptionFor(java.lang.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.java.util.Map<FuzzyMap.IKey,ParameterDescription>getDescriptions()java.util.Map<Parameterized,ParameterDescription>getFields()JCommander.MainParametergetMainParameter()java.lang.StringgetMainParameterDescription()ParameterDescriptiongetMainParameterValue()java.util.List<java.lang.Object>getObjects()JCommander.OptionsgetOptions()java.util.Comparator<? super ParameterDescription>getParameterDescriptionComparator()java.util.List<ParameterDescription>getParameters()java.lang.StringgetParsedAlias()The name of the command or the alias in the form it was passed to the command line.java.lang.StringgetParsedCommand()private ParameterDescriptiongetPrefixDescriptionFor(java.lang.String arg)java.lang.StringgetProgramDisplayName()Get the program display name (used only in the usage).java.lang.StringgetProgramName()Get the program name (used only in the usage).java.util.Map<JCommander.ProgramName,JCommander>getRawCommands()private java.lang.StringgetSeparatorFor(java.lang.String arg)java.util.List<java.lang.String>getUnknownOptions()IUsageFormattergetUsageFormatter()Returns the usage formatter.private voidhandleBooleanOption(ParameterDescription pd, java.lang.Class<?> fieldType)private voidinitializeDefaultValue(ParameterDescription pd)private voidinitializeDefaultValues()private voidinitMainParameterValue(java.lang.String arg)Init the main parameter with the given arg.private static <T> TinstantiateConverter(java.lang.String optionName, java.lang.Class<? extends T> converterClass)private booleanisBooleanType(java.lang.Class<?> fieldType)private booleanisOption(java.lang.String passedArg)booleanisParameterOverwritingAllowed()private booleanmatchArg(java.lang.String arg, FuzzyMap.IKey key)static JCommander.BuildernewBuilder()private voidp(java.lang.String string)private voidparse(boolean validate, java.lang.String... args)voidparse(java.lang.String... args)Parse and validate the command line parameters.private voidparseValues(java.lang.String[] args, boolean validate)Main method that parses the values and initializes the fields accordingly.voidparseWithoutValidation(java.lang.String... args)Parse the command line parameters without validating them.private static java.lang.Stringpluralize(int quantity, java.lang.String singular, java.lang.String plural)private intprocessFixedArity(java.lang.String[] args, int index, ParameterDescription pd, boolean validate, java.lang.Class<?> fieldType)private intprocessFixedArity(java.lang.String[] args, int originalIndex, ParameterDescription pd, boolean validate, java.lang.Class<?> fieldType, int arity)private intprocessPassword(java.lang.String[] args, int index, ParameterDescription pd, boolean validate)private intprocessVariableArity(java.lang.String[] args, int index, ParameterDescription pd, boolean validate)private java.util.List<java.lang.String>readFile(java.lang.String fileName)Reads the file specified by filename and returns the file content as a string.private char[]readPassword(java.lang.String description, boolean echoInput)Invoke Console.readPassword through reflection to avoid depending on Java 6.private java.lang.Strings(int count)voidsetAcceptUnknownOptions(boolean b)voidsetAllowAbbreviatedOptions(boolean b)voidsetAllowParameterOverwriting(boolean b)voidsetAtFileCharset(java.nio.charset.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.voidsetDescriptionsBundle(java.util.ResourceBundle bundle)Sets theResourceBundleto use for looking up descriptions.voidsetExpandAtSign(boolean expandAtSign)Disables expanding@file.voidsetParameterDescriptionComparator(java.util.Comparator<? super ParameterDescription> c)voidsetProgramName(java.lang.String name)Set the program name (used only in the usage).voidsetProgramName(java.lang.String name, java.lang.String... aliases)Set the program namevoidsetUsageFormatter(IUsageFormatter usageFormatter)Sets the usage formatter.voidsetVerbose(int verbose)private java.lang.String[]subArray(java.lang.String[] args, int index)private static java.lang.Stringtrim(java.lang.String string)Remove spaces at both ends and handle double quotes.private static <T> TtryInstantiateConverter(java.lang.String optionName, java.lang.Class<T> converterClass)voidusage()Prints the usage ongetConsole()using the underlyingusageFormatter.private voidvalidateOptions()Make sure that all the required parameters have received a value.
-
-
-
Field Detail
-
DEBUG_PROPERTY
public static final java.lang.String DEBUG_PROPERTY
- See Also:
- Constant Field Values
-
descriptions
private java.util.Map<FuzzyMap.IKey,ParameterDescription> descriptions
A map to look up parameter description per option name.
-
objects
private java.util.List<java.lang.Object> objects
The objects that contain fields annotated with @Parameter.
-
usageFormatter
private IUsageFormatter usageFormatter
The usage formatter to use inusage().
-
mainParameter
private JCommander.MainParameter mainParameter
-
requiredFields
private java.util.Map<Parameterized,ParameterDescription> 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
private java.util.Map<Parameterized,ParameterDescription> fields
A map of all the parameterized fields/methods.
-
commands
private java.util.Map<JCommander.ProgramName,JCommander> commands
List of commands and their instance.
-
aliasMap
private java.util.Map<FuzzyMap.IKey,JCommander.ProgramName> aliasMap
Alias database for reverse lookup
-
parsedCommand
private java.lang.String parsedCommand
The name of the command after the parsing has run.
-
parsedAlias
private java.lang.String parsedAlias
The name of command or alias as it was passed to the command line
-
programName
private JCommander.ProgramName programName
-
helpWasSpecified
private boolean helpWasSpecified
-
unknownArgs
private java.util.List<java.lang.String> unknownArgs
-
console
private Console console
-
options
private final JCommander.Options options
-
DEFAULT_VARIABLE_ARITY
private final IVariableArity DEFAULT_VARIABLE_ARITY
-
-
Constructor Detail
-
JCommander
private JCommander(JCommander.Options options)
-
JCommander
public JCommander()
Creates a new un-configured JCommander object.
-
JCommander
public JCommander(java.lang.Object object)
- Parameters:
object- The arg object expected to containParameterannotations.
-
JCommander
public JCommander(java.lang.Object object, java.util.ResourceBundle bundle)- Parameters:
object- The arg object expected to containParameterannotations.bundle- The bundle to use for the descriptions. Can be null.
-
JCommander
public JCommander(java.lang.Object object, java.util.ResourceBundle bundle, java.lang.String... args)- 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 public JCommander(java.lang.Object object, java.lang.String... args)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 Detail
-
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
public void setConsole(Console console)
-
getConsole
public Console getConsole()
- Returns:
- a wrapper for a
PrintStream, typicallySystem.out.
-
addObject
public final void addObject(java.lang.Object object)
Adds the provided arg object to the set of objects that this commander will parse arguments into.- Parameters:
object- The arg object expected to containParameterannotations. Ifobjectis an array or isIterable, the child objects will be added instead.
-
setDescriptionsBundle
public final void setDescriptionsBundle(java.util.ResourceBundle bundle)
Sets theResourceBundleto use for looking up descriptions. Set this tonullto use description text directly.
-
parse
public void parse(java.lang.String... args)
Parse and validate the command line parameters.
-
parseWithoutValidation
public void parseWithoutValidation(java.lang.String... args)
Parse the command line parameters without validating them.
-
parse
private void parse(boolean validate, java.lang.String... args)
-
initializeDefaultValues
private void initializeDefaultValues()
-
validateOptions
private void validateOptions()
Make sure that all the required parameters have received a value.
-
pluralize
private static java.lang.String pluralize(int quantity, java.lang.String singular, java.lang.String plural)
-
expandArgs
private java.lang.String[] expandArgs(java.lang.String[] originalArgv)
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
private java.util.List<java.lang.String> expandDynamicArg(java.lang.String arg)
-
matchArg
private boolean matchArg(java.lang.String arg, FuzzyMap.IKey key)
-
isOption
private boolean isOption(java.lang.String passedArg)
-
getPrefixDescriptionFor
private ParameterDescription getPrefixDescriptionFor(java.lang.String arg)
-
getDescriptionFor
private ParameterDescription getDescriptionFor(java.lang.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.
-
getSeparatorFor
private java.lang.String getSeparatorFor(java.lang.String arg)
-
readFile
private java.util.List<java.lang.String> readFile(java.lang.String fileName)
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
private static java.lang.String trim(java.lang.String string)
Remove spaces at both ends and handle double quotes.
-
createDescriptions
public void createDescriptions()
Create the ParameterDescriptions for all the \@Parameter found.
-
addDescription
private void addDescription(java.lang.Object object)
-
initializeDefaultValue
private void initializeDefaultValue(ParameterDescription pd)
-
parseValues
private void parseValues(java.lang.String[] args, boolean validate)Main method that parses the values and initializes the fields accordingly.
-
isBooleanType
private boolean isBooleanType(java.lang.Class<?> fieldType)
-
handleBooleanOption
private void handleBooleanOption(ParameterDescription pd, java.lang.Class<?> fieldType)
-
determineArity
private final int determineArity(java.lang.String[] args, int index, ParameterDescription pd, IVariableArity va)
-
processPassword
private int processPassword(java.lang.String[] args, int index, ParameterDescription pd, boolean validate)- Returns:
- the number of options that were processed.
-
processVariableArity
private int processVariableArity(java.lang.String[] args, int index, ParameterDescription pd, boolean validate)- Returns:
- the number of options that were processed.
-
processFixedArity
private int processFixedArity(java.lang.String[] args, int index, ParameterDescription pd, boolean validate, java.lang.Class<?> fieldType)
-
processFixedArity
private int processFixedArity(java.lang.String[] args, int originalIndex, ParameterDescription pd, boolean validate, java.lang.Class<?> fieldType, int arity)
-
readPassword
private char[] readPassword(java.lang.String description, boolean echoInput)Invoke Console.readPassword through reflection to avoid depending on Java 6.
-
subArray
private java.lang.String[] subArray(java.lang.String[] args, int index)
-
initMainParameterValue
private void initMainParameterValue(java.lang.String arg)
Init the main parameter with the given arg. Note that the main parameter can be either a Listor a single value.
-
getMainParameterDescription
public java.lang.String getMainParameterDescription()
-
setProgramName
public void setProgramName(java.lang.String name)
Set the program name (used only in the usage).
-
getProgramName
public java.lang.String getProgramName()
Get the program name (used only in the usage).
-
getProgramDisplayName
public java.lang.String getProgramDisplayName()
Get the program display name (used only in the usage).
-
setProgramName
public void setProgramName(java.lang.String name, java.lang.String... aliases)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
public void setUsageFormatter(IUsageFormatter usageFormatter)
Sets the usage formatter.- Parameters:
usageFormatter- the usage formatter- Throws:
java.lang.IllegalArgumentException- if the argument is null
-
getUsageFormatter
public IUsageFormatter getUsageFormatter()
Returns the usage formatter.- Returns:
- the usage formatter
-
getOptions
public JCommander.Options getOptions()
-
getDescriptions
public java.util.Map<FuzzyMap.IKey,ParameterDescription> getDescriptions()
-
getMainParameter
public JCommander.MainParameter getMainParameter()
-
newBuilder
public static JCommander.Builder newBuilder()
-
getFields
public java.util.Map<Parameterized,ParameterDescription> getFields()
-
getParameterDescriptionComparator
public java.util.Comparator<? super ParameterDescription> getParameterDescriptionComparator()
-
setParameterDescriptionComparator
public void setParameterDescriptionComparator(java.util.Comparator<? super ParameterDescription> c)
-
setColumnSize
public void setColumnSize(int columnSize)
-
getColumnSize
public int getColumnSize()
-
getBundle
public java.util.ResourceBundle getBundle()
-
getParameters
public java.util.List<ParameterDescription> 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
public ParameterDescription getMainParameterValue()
- Returns:
- the main parameter description or null if none is defined.
-
p
private void p(java.lang.String string)
-
setDefaultProvider
public void setDefaultProvider(IDefaultProvider defaultProvider)
Define the default provider for this instance.
-
addConverterFactory
public void addConverterFactory(IStringConverterFactory converterFactory)
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
public void addConverterInstanceFactory(IStringConverterInstanceFactory converterInstanceFactory)
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, java.lang.Class<?> forType, java.lang.String optionName)
-
convertValue
public java.lang.Object convertValue(Parameterized parameterized, java.lang.Class type, java.lang.String optionName, java.lang.String value)
- Parameters:
type- The type of the actual parameteroptionName-value- The value to convert
-
tryInstantiateConverter
private static <T> T tryInstantiateConverter(java.lang.String optionName, java.lang.Class<T> converterClass)
-
instantiateConverter
private static <T> T instantiateConverter(java.lang.String optionName, java.lang.Class<? extends T> converterClass) throws java.lang.InstantiationException, java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException- Throws:
java.lang.InstantiationExceptionjava.lang.IllegalAccessExceptionjava.lang.reflect.InvocationTargetException
-
addCommand
public void addCommand(java.lang.String name, java.lang.Object object)Add a command object.
-
addCommand
public void addCommand(java.lang.Object object)
-
addCommand
public void addCommand(java.lang.String name, java.lang.Object object, java.lang.String... aliases)Add a command object and its aliases.
-
getCommands
public java.util.Map<java.lang.String,JCommander> getCommands()
-
getRawCommands
public java.util.Map<JCommander.ProgramName,JCommander> getRawCommands()
-
getParsedCommand
public java.lang.String getParsedCommand()
-
getParsedAlias
public java.lang.String 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
private java.lang.String s(int count)
- Returns:
- n spaces
-
getObjects
public java.util.List<java.lang.Object> getObjects()
- Returns:
- the objects that JCommander will fill with the result of parsing the command line.
-
findParameterDescription
private ParameterDescription findParameterDescription(java.lang.String arg)
-
findCommand
private JCommander findCommand(JCommander.ProgramName name)
-
findProgramName
private JCommander.ProgramName findProgramName(java.lang.String name)
-
findCommandByAlias
public JCommander findCommandByAlias(java.lang.String commandOrAlias)
-
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
public java.util.List<java.lang.String> getUnknownOptions()
-
setAllowParameterOverwriting
public void setAllowParameterOverwriting(boolean b)
-
isParameterOverwritingAllowed
public boolean isParameterOverwritingAllowed()
-
setAtFileCharset
public void setAtFileCharset(java.nio.charset.Charset charset)
Sets the charset used to expand@files.- Parameters:
charset- the charset
-
-