jcommander 是一个方便的java 命令行解析包,使用简单、方便,我们可以在好多开源项目中看到
次工具包的身影,以下是一个简单的使用
环境准备
- 项目结构
├── pom.xml
└── src
├── main
│ ├── java
│ │ └── com
│ │ └── dalong
│ │ └── Application.java
│ └── resources
└── test
└── java
- 代码说明
此项目是一个典型的maven 项目,开发的为flat 模式的java 应用 pom.xml 文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dalong</groupId>
<artifactId>commander</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<encoding>UTF-8</encoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.beust</groupId>
<artifactId>jcommander</artifactId>
<version>1.78</version>
</dependency>
</dependencies>
<build>
<!-- Maven Shade Plugin -->
<finalName>jcommander-app</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<executions>
<!-- Run shade goal on package phase -->
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<!-- add Main-Class to manifest file -->
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.dalong.Application</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
java 代码 com.dalong.Application.java 使用jcommander 工具包
package com.dalong;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
public class Application {
@Parameter(names={"--length", "-l"},help = true,required =true ,description = "this is length info")
int length;
@Parameter(names={"--pattern", "-p"},help = true,required =true ,description = "this is pattern info")
int pattern;
@Parameter(names = "--help", help = true)
private boolean help;
public static void main(String[] args) {
Application main = new Application();
JCommander jct = JCommander.newBuilder()
.addObject(main)
.build();
jct.setProgramName("demo app");
try {
jct.parse(args);
// 提供帮助说明
if (main.help) {
jct.usage();
return;
}
main.run();
}
catch (ParameterException parameterException ){
// 为了方便使用,同时输出exception的message
System.out.printf(parameterException.toString()+"
");
jct.usage();
}
}
public void run() {
System.out.printf("%d %d", length, pattern);
}
}
使用
- 构建
mvn clean package
- 使用
java -jar target/jcommander-app.jar
- 效果
参考资料
https://github.com/cbeust/jcommander
https://github.com/rongfengliang/jcommander-learning