GoogleOptions命令行参数解析工具
- GoogleOptions
GoogleOptions
GoogleOptions是来自 Bazel Project 的命令行参数解析器。将 com.google.devtools.common.options
包拆分为一个单独的 jar,用于通用实用程序。
环境搭建:
- 引入maven依赖
<dependency>
<groupId>com.github.pcj</groupId>
<artifactId>google-options</artifactId>
<version>1.0.0</version>
</dependency>
- 引入官方提供的示例Demo
package example;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionsBase;
import java.util.List;
/**
* Command-line options definition for example server.
*/
public class ServerOptions extends OptionsBase {
@Option(
name = "help",
abbrev = 'h',
help = "Prints usage info.",
defaultValue = "true"
)
public boolean help;
@Option(
name = "host",
abbrev = 'o',
help = "The server host.",
category = "startup",
defaultValue = ""
)
public String host;
@Option(
name = "port",
abbrev = 'p',
help = "The server port.",
category = "startup",
defaultValue = "8080"
)
public int port;
@Option(
name = "dir",
abbrev = 'd',
help = "Name of directory to serve static files.",
category = "startup",
allowMultiple = true,
defaultValue = ""
)
public List<String> dirs;
}
Option注解参数说明
- name:选项名称
- defaultValue:默认值
- abbrev:选项的单字符缩写
- help:使用信息的帮助字符串
- category:描述此选项所属的类别
- allowMultiple:一个标志,指示是否应允许选项类型在单个选项列表中多次出现。
实际使用:
package example;
import com.google.devtools.common.options.OptionsParser;
import java.util.Collections;
public class Server {
//java -jar server.jar --host=127.0.0.1 --port=21 --dir=E:\test --dir=E:\demo
public static void main(String[] args) {
OptionsParser parser = OptionsParser.newOptionsParser(ServerOptions.class);
parser.parseAndExitUponError(args);
ServerOptions options = parser.getOptions(ServerOptions.class);
if (options.host.isEmpty() || options.port < 0 || options.dirs.isEmpty()) {
printUsage(parser);
return;
}
System.out.format("Starting server at %s:%d...\n", options.host, options.port);
for (String dirname : options.dirs) {
System.out.format("\\--> Serving static files at <%s>\n", dirname);
}
}
private static void printUsage(OptionsParser parser) {
System.out.println("Usage: java -jar server.jar OPTIONS");
System.out.println(parser.describeOptions(Collections.<String, String>emptyMap(),
OptionsParser.HelpVerbosity.LONG));
}
}