您的位置:首页 > 运维架构

CommandLine 和 Options

2016-08-05 18:37 239 查看
用到的jar包

<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.3.1</version>
</dependency>


Option 的格式

Option(String opt, String longOpt, boolean hasArg, String description)
选项名,选项全称,是否有参数(如果true时没有参数会抛异常),描述
例如:
new Option("h","help",false,"print help");

Option 合法性校验

OptionValidator.class

/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0 *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.commons.cli;

/**
* Validates an Option string.
*
* @version $Id: OptionValidator.java 1544819 2013-11-23 15:34:31Z tn $
* @since 1.1
*/
final class OptionValidator
{
/**
* Validates whether <code>opt</code> is a permissible Option
* shortOpt.  The rules that specify if the <code>opt</code>
* is valid are:
*
* <ul>
*  <li>a single character <code>opt</code> that is either
*  ' '(special case), '?', '@' or a letter</li>
*  <li>a multi character <code>opt</code> that only contains
*  letters.</li>
* </ul>
* <p>
* In case {@code opt} is {@code null} no further validation is performed.
*
* @param opt The option string to validate, may be null
* @throws IllegalArgumentException if the Option is not valid.
*/
static void validateOption(String opt) throws IllegalArgumentException
{
// if opt is NULL do not check further
if (opt == null)
{
return;
}

// handle the single character opt
if (opt.length() == 1)
{
char ch = opt.charAt(0);

if (!isValidOpt(ch))
{
throw new IllegalArgumentException("Illegal option name '" + ch + "'");
}
}

// handle the multi character opt
else
{
for (char ch : opt.toCharArray())
{
if (!isValidChar(ch))
{
throw new IllegalArgumentException("The option '" + opt + "' contains an illegal "
+ "character : '" + ch + "'");
}
}
}
}

/**
* Returns whether the specified character is a valid Option.
*
* @param c the option to validate
* @return true if <code>c</code> is a letter, '?' or '@', otherwise false.
*/
private static boolean isValidOpt(char c)
{
return isValidChar(c) || c == '?' || c == '@';
}

/**
* Returns whether the specified character is a valid character.
*
* @param c the character to validate
* @return true if <code>c</code> is a letter.
*/
private static boolean isValidChar(char c)
{
return Character.isJavaIdentifierPart(c);
}
}


View Code
常见异常

org.apache.commons.cli.UnrecognizedOptionException

org.apache.commons.cli.MissingOptionException

org.apache.commons.cli.MissingArgumentException

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

如果args开启某option,但options中不包含时,未识别选项

如果args开启某option,该option已设置为包含参数,但args 中没有该option参数时,丢失参数

如果某option已设置为必须,但args中未开启该option是,丢失选项

小样

package cli;

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 TestCommandline {
public static void main(String[] args) throws ParseException {
Options options = new Options();
Option opt = new Option("n", "namesrvAddr", true,
"Name server address list, eg: 192.168.0.1:9876;192.168.0.2:9876");
opt.setRequired(false);
options.addOption(opt);

CommandLineParser parser = new DefaultParser();
CommandLine commandLine = parser.parse(options, args);

String optNmae = "n";
if (commandLine.hasOption(optNmae)) {
System.out.println(commandLine.getOptionValue(optNmae));
for (String s : commandLine.getOptionValues(optNmae)) {
System.out.print(s+" ");
}
}
}
}


入参:

-n 192.168.0.1:9876 -n 192.168.0.2:9876

结果:

192.168.0.1:9876
192.168.0.1:9876 192.168.0.2:9876

小结

必须由『-』开启选项,短横后面需合法,由空格(不限个数)区分选项和参数。

一个选项只能跟一个参数。

选项参数对之外的自动忽略。

两个相同的选项参数由左至右依次被设置到参数数组中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: