java @option之args4j

args4j简介

args4j是一个用来配置命令行的工具。 
在实际的项目中用到命令行的并不是很常见,但当真正使用到时,特别是在程序启动时配置一下参数的时候就很有用了,如果参数很多的话,一个一个解析命令行还是比较麻烦的.这时使用Args4J就相当好办了. 在本文中我们来看看Args4J的使用,当需要时能提供一个解决方案. 
Args4J使用一个被称为Option类的类来保存输入的参数,让后根据该类来应用参数,每个参数可以对应一个类中的属性,该属性用Annotation注释,在Annotation中给出该参数 的选项, 还可以配置其他有用的信息

例如,在做开源工具时,写好一个项目,需要上传到Linux等平台时,往往就需要通过命令输入程序的参数。如下,是我在cmd里面做测试用的。 
这里写图片描述

从上面可以看到,输入的参数有两个,一个是inputfdir,一个是outfdir。

使用样例

程序目录结构如下 
这里写图片描述

package main;

import org.kohsuke.args4j.Option;

public class SampleCmdOption {

    @Option(name="-est", usage="Specify whether we want to estimate model from scratch")
    public boolean est = false;

    @Option(name="-estc", usage="Specify whether we want to continue the last estimation")
    public boolean estc = false;

    @Option(name="-inf", usage="Specify whether we want to do inference")
    public boolean inf = true;

}
package main;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;

public class TestMain {

    public static void main(String[] args) {

        //开始解析命令参数
        SampleCmdOption option  = new SampleCmdOption();
        CmdLineParser parser = new CmdLineParser(option);

        try {

            if (args.length == 0){
                showHelp(parser);
                return;
            }

            parser.parseArgument(args);

            //开始初步参数校验并调用程序开始运行,这里就会获得参数
            System.out.println(option.est);
            System.out.println(option.name);
            //下面再写你自己的主程序都是可以的。。。。。

        }catch (CmdLineException cle){
            System.out.println("Command line error: " + cle.getMessage());
            showHelp(parser);
            return;
        }catch (Exception e){
            System.out.println("Error in main: " + e.getMessage());
            e.printStackTrace();
            return;
        }

    }

    public static void showHelp(CmdLineParser parser){
        System.out.println("LDA [options ...] [arguments...]");
        parser.printUsage(System.out);
    }

}
原文地址:https://www.cnblogs.com/smuxiaolei/p/7473407.html