java apache cli_java – 如何使用apache commons cli指定多个选项?

您不能拥有上下文相关的参数.您可以拥有以下参数:job1,job2,job3,C& W,但你不能说(通过图书馆)C& W仅对job1有效.

如果job1 / 2/3是互斥的,则创建一个OptionGroup.然后在代码中,确保C& W仅用于job1.

import org.apache.commons.cli.CommandLine;

import org.apache.commons.cli.CommandLineParser;

import org.apache.commons.cli.GnuParser;

import org.apache.commons.cli.Option;

import org.apache.commons.cli.OptionBuilder;

import org.apache.commons.cli.OptionGroup;

import org.apache.commons.cli.Options;

import org.apache.commons.cli.HelpFormatter;

public class StackOverflowExample

{

public static final String JOB1 = "job1";

public static final Option job1 =

OptionBuilder.hasArg(false)

.isRequired(false)

.withDescription("description of job1")

.create(JOB1);

public static final String JOB2 = "job2";

public static final Option job2 =

OptionBuilder.hasArg(false)

.isRequired(false)

.withDescription("description of job2")

.create(JOB2);

public static final String JOB3 = "job3";

public static final Option job3 =

OptionBuilder.hasArg(false)

.isRequired(false)

.withDescription("description of job3")

.create(JOB3);

public static final String MY_C = "C";

public static final Option my_c =

OptionBuilder.hasArg(true)

.withArgName("count")

.isRequired(false)

.withDescription("description of C")

.create(MY_C);

public static final String MY_W = "W";

public static final Option my_w =

OptionBuilder.hasArg(true)

.withArgName("width")

.isRequired(false)

.withDescription("description of W")

.create(MY_W);

public static void main(String[] args)

{

Options options = new Options();

OptionGroup optgrp = new OptionGroup();

optgrp.addOption(job1);

optgrp.addOption(job2);

optgrp.addOption(job3);

options.addOptionGroup(optgrp);

options.addOption(my_c);

options.addOption(my_w);

try {

CommandLineParser parser = new GnuParser();

CommandLine cmdline = parser.parse(options, args);

if (((cmdline.hasOption(MY_C)) || (cmdline.hasOption(MY_W))) &&

(! cmdline.hasOption(JOB1))) {

HelpFormatter help = new HelpFormatter();

help.printHelp("cmdname", options);

System.exit(-1);

}

System.out.println("OK");

}

catch (Exception ex) {

ex.printStackTrace();

System.exit(-1);

}

}

}

其中产生以下输出:

$javac -d . -cp ~/sandbox/CoreUtils/lib/commons-cli-1.2.jar:. StackOverflowExample.java

$java -cp ~/sandbox/CoreUtils/lib/commons-cli-1.2.jar:. StackOverflowExample -C foo -job1

OK

$java -cp ~/sandbox/CoreUtils/lib/commons-cli-1.2.jar:. StackOverflowExample -C foo -job2

usage: cmdname

-C description of C

-job1 description of job1

-job2 description of job2

-job3 description of job3

-W description of W

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值