zoukankan      html  css  js  c++  java
  • 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);
        }
    
    }
  • 相关阅读:
    JavaScript控制改变鼠标的形状
    web控件开发系列(四) 自定义控件属性(上)
    web控件开发系列() 基础介绍
    Web前端面试题 Js把URL中的参数解析为一个对象
    节点的操作 创建、添加、移除、移动、复制
    一个sohoto广告弹出页提取时间的Js修改过程
    FireFox支持innerText的方法
    Js 基于html5localStorage方法 制作的 "我的便签本"
    原生JavaScript对CSS进行格式化和压缩
    JavaScript 命名规则 变量命名规则
  • 原文地址:https://www.cnblogs.com/smuxiaolei/p/7473407.html
Copyright © 2011-2022 走看看