It’s so easy to make a command line program in Java!
Picocli is the most complete and easiest-to-use command line development framework in Java that I personally think can help everyone quickly develop command line tools.
There are very few tutorials about the Picocli framework on the Internet. The most recommended way to get started is to read the official documentation in addition to the tutorials on Fish Skin.
Official documentation: https://picocli.info/
It is recommended to start with the official quick start tutorial: https://picocli.info/quick-guide.html
Generally, our steps for learning new technologies are: first run through the introductory demo, and then learn the usage and features of the technology.
Getting started demo
Introduce the picocli dependency into the
pom.xml
file of the Maven project:1
2
3
4
5
6<!-- https://picocli.info -->
<dependency>
<groupId>info.picocli</groupId>
<artifactId>picocli</artifactId>
<version>4.7.5</version>
</dependency>
Then we create a new cli.example package under the com.yupi package to store all sample codes related to getting started with Picocli.
- Copy the example code in the official quick start tutorial to the
com.yupi.cli.example
package, and slightly modify the code in the run method to print the values of the parameters.
1 | package com.yupi.cli.example; |
- Create a class that implements the
Runnable
orCallable
interface, which is a command. - Mark the class with the
@Command
annotation and name it, and set themixinStandardHelpOptions
attribute to true to automatically add--help
and--version
options to the application. - Set the field as a command line option through the
@Option
annotation. You can set a name and description for the option. - Set the field as a command line parameter through the
@Parameters
annotation, and you can specify the default value, description and other information. - Picocli will convert the command line parameters into strongly typed values and automatically inject them into the annotation fields.
- Define business logic in the
run
orcall
method of the class, which will be called when the command is parsed successfully (the user hits Enter). - In the
main
method, the command input by the user is processed through theexecute
method of theCommandLine
object, and the rest is left to the Picocli framework to parse the command and execute the business logic~ - The
CommandLine.execute
method returns an exit code. You can callSystem.exit
with this exit code as a parameter to indicate success or failure to the calling process.
Through this introductory demo, we can briefly summarize the development process of a command:
- Create a command
- Set options and parameters
- Write business logic for command execution
- Accept input and execute commands through the CommandLine object
After running through the introductory demo, let’s learn some practical functions of the Picocli development command line.