核心能力
- 定義選項規則 (短/長名、是否需參數、描述)
- 自動解析
String[] args,類型轉換
- 生成標準用法幫助信息
- 支援 POSIX、GNU、Java 等多種風格
Maven 依賴
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
</dependency>
完整範例:互動式命令解析
public class OptionsTip {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = in.readLine(); // 從控制檯讀取命令行
args = line.split(" ");
Options options = new Options();
options.addOption("h", false, "Print help for this application");
options.addOption("u", true, "The username to use");
options.addOption("dsn", true, "The data source to use");
CommandLineParser parser = new BasicParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption('h')) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("OptionsTip", options);
} else {
System.out.println("Username: " + cmd.getOptionValue("u"));
System.out.println("DataSource: " + cmd.getOptionValue("dsn"));
}
}
}
執行效果
輸入: -h
輸出:
usage: OptionsTip
-dsn <arg> The data source to use
-h Print help for this application
-u <arg> The username to use
輸入: -u admin -dsn mysql
輸出:
Username: admin
DataSource: mysql
進階特性
- OptionGroup:互斥選項組
- PatternOptionBuilder:簡化選項定義語法
- GnuParser / PosixParser:支援長選項 (
--username)、短選項合併 (-uv)
- 類型轉換:
cmd.getOptionValue("port", Integer.class)
最佳實踐
- 在
main 入口統一解析,構建配置對象
- 區分必選/可選選項,缺失時拋出友好錯誤
- 整合
HelpFormatter 提供自助文檔