■ コマンドライン引数のパーサー
[1] Apache Commons CLI << ★今回はこっち [2] args4jargs4j については、以下の関連記事を参照のこと。
https://blogs.yahoo.co.jp/dk521123/37217932.html
■ Apache Commons CLI
http://commons.apache.org/ダウンロード
ftp://ftp.kddilabs.jp/infosystems/apache/commons/cli/binaries/Gradle
compile 'commons-cli:commons-cli:1.4'
■ サンプル
import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class Demo { public static void main(String[] args) throws ParseException { Option portOption = Option.builder("p").longOpt("port").hasArg().required(false).type(Number.class) .desc("Port this server listens on").build(); Option threadsOption = Option.builder("t").longOpt("threads").hasArg().required(false).type(Number.class) .desc("Max Threads").build(); Option debugOption = Option.builder("d").longOpt("debug").required(false).type(Boolean.class).desc("Debug Mode") .build(); Options options = new Options(); options.addOption(portOption); options.addOption(threadsOption); options.addOption(debugOption); String[] args1 = { "-p", "18080", "-t", "10", "-d" }; CommandLineParser parser = new DefaultParser(); CommandLine commandLine = parser.parse(options, args1); int port = commandLine.hasOption("port") ? ((Number) (commandLine.getParsedOptionValue("port"))).intValue() : 8080; int maxThreads = commandLine.hasOption("threads") ? ((Number) (commandLine.getParsedOptionValue("threads"))).intValue() : 5; boolean isDebug = commandLine.hasOption("debug") ? true : false; System.out.println("Port:" + port); System.out.println("MaxThreads:" + maxThreads); System.out.println("Debug:" + isDebug); } }
出力結果
Port:18080 MaxThreads:10 Debug:true
参考文献
http://netbuffalo.doorblog.jp/archives/4463292.htmlhttp://d.hatena.ne.jp/cactusman/20081129/p1
https://qiita.com/opengl-8080/items/629947d3c5a5f38ba6d5
Apache Commons CLI
https://www.programcreek.com/java-api-examples/org.apache.commons.cli.CommandLineParserhttp://m12i.hatenablog.com/entry/2015/05/25/222827