java 如何在 apache commons-cli 中使用命令行和选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13526112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:05:57  来源:igfitidea点击:

how to use CommandLine and Options in apache commons-cli

javaapache-commons-cli

提问by buttowski

This is first time am using apache commons-cli.

这是我第一次使用 apache commons-cli。

Requirement : i want to use CommandLine and Options in commons-cli to pass my runtime parameters to my java class.

要求:我想在 commons-cli 中使用命令行和选项将我的运行时参数传递给我的 java 类。

Scenario : main class - com.test.mian.MyClass

场景:主类 - com.test.mian.MyClass

i can run my class from command line by

我可以从命令行运行我的课程

java -cp $classPath  com.test.mian.MyClass -one 1 -two 2 -three 3

how can i do the same from a method of another class by passing these arguments using CommandLine and Options of commons-cli.

我如何通过使用 Commons-cli 的命令行和选项传递这些参数来从另一个类的方法中执行相同的操作。

and also if there is any other way other than

并且如果有任何其他方式而不是

System.setProperty("key","value");

please suggest too.

请也提出建议。

采纳答案by Joe Casadonte

Here's a verystripped down version of something I use. It basically sets up a singleton that gets initialized once and then can be used wherever you want within your program. I chose to store the info in HashMap's and ArrayList's because they were easier to deal with later.

这是我使用的东西的一个非常精简的版本。它基本上设置了一个初始化一次的单例,然后可以在程序中的任何地方使用。我选择将信息存储在 HashMap 和 ArrayList 中,因为它们以后更容易处理。

//****************************************************************************
//***** File Name: MianCLIOptions.java
//****************************************************************************

package com.test.mian;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.cli.AlreadySelectedException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.MissingArgumentException;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.apache.commons.lang.WordUtils;


//****************************************************************************
//****************************************************************************
//****************************************************************************
//****************************************************************************
public class MianCLIOptions
{
    //***** constants *****

    //***** public data members *****

    //***** private data members *****
    private static MianCLIOptions singletonObj = null;

    private HashMap<String,Object> options = new HashMap<String,Object>();
    private ArrayList<String> arguments = new ArrayList<String>();

    //****************************************************************************
    public static MianCLIOptions getopts()
    {
        if (singletonObj == null) {
            throw new IllegalStateException("[MianCLIOptions] Command line not yet initialized.");
        }

        return singletonObj;
    }

    //****************************************************************************
    public static synchronized void initialize(Options optsdef, String[] args)
        throws MianCLIOptionsException, UnrecognizedOptionException, MissingArgumentException,
               MissingOptionException, AlreadySelectedException, ParseException
    {
        if (singletonObj == null) {
            singletonObj = new MianCLIOptions(optsdef, args);
        }
        else {
            throw new IllegalStateException("[MianCLIOptions] Command line already initialized.");
        }
    }

    //****************************************************************************
    //----- prevent cloning -----
    public Object clone() throws CloneNotSupportedException
    {
        throw new CloneNotSupportedException();
    }

    //****************************************************************************
    public boolean isset(String opt)
    {
        return options.containsKey(opt);
    }

    //****************************************************************************
    public Object getopt(String opt)
    {
        Object rc = null;

        if (options.containsKey(opt)) {
            rc = options.get(opt);
        }

        return rc;
    }

    //****************************************************************************
    //***** finally parse the command line
    //****************************************************************************
    private MianCLIOptions(Options optsdef, String[] args)
        throws UnrecognizedOptionException, MissingArgumentException,
               MissingOptionException, AlreadySelectedException, ParseException
    {
        //***** (blindly) parse the command line *****
        CommandLineParser parser = new GnuParser();
        CommandLine cmdline = parser.parse(optsdef, args);

        //***** store options and arguments *****
        //----- options -----
        for (Option opt : cmdline.getOptions()) {
            String key = opt.getOpt();
            if (opt.hasArgs()) {
                options.put(key, opt.getValuesList());
            }
            else {
                options.put(key, opt.getValue());
            }
        }

        //----- arguments -----
        for (String str : cmdline.getArgs()) {
            //----- account for ant/build.xml/generic -----
            if (str.length() > 0) {
                arguments.add(str);
            }
        }
    }
}

//****************************************************************************
//***** EOF  ***** EOF  ***** EOF  ***** EOF  ***** EOF  ***** EOF  **********

In your main, you can then call it like so:

在您的主要内容中,您可以像这样调用它:

    //***** build up options *****
    Options options = new Options();

    // ... .... ...

    //***** process command line *****
    try {
        MianCLIOptions.initialize(options, args);
    }
    catch (UnrecognizedOptionException ex) {
        // do something
    }

And finally, in some other class you can call it like so:

最后,在其他一些类中,您可以这样称呼它:

    MianCLIOptions opts = MianCLIOptions.getopts();
    if (opts.isset("someopt")) {
        // do something exciting
    }

Hope that helps!

希望有帮助!