如何使用JCommander

时间:2016-01-08 10:46:25

标签: java jcommander

我有一个示例代码我下载并想运行它,问题是它使用JCommander加载一些配置,我没有配置文件但它想加载一个,所以我想知道;我如何使用JCommander,我阅读文档并根据网站使用它来解析命令行参数但我真的不明白这意味着什么,这个错误实际上阻碍了我做我的项目,这里是代码请求对于.conf文件:

         BasicConfigurator.configure(); // TODO: config from options

        // Parse the command line options
        CliOptions options = new CliOptions();
        new JCommander(options, args);

        if (StringUtils.isBlank(options.configFile))
        {
            options.configFile = "/etc/car-counter/car-counter.conf";
        }

        // Read in the configuration
        Wini ini = new Wini();
        ini.getConfig().setMultiOption(true);
        ini.load(new File(options.configFile));

        new DefaultProcessor(ini).process();

这里是CliOption类

public class CliOptions
{
@Parameter(names = { "-c", "--config" }, description = "Sets the location of the configuration file.")
public String configFile;

}

1 个答案:

答案 0 :(得分:1)

JCommander背后的想法是有一个简单的可配置选项来提供命令行参数,它们的默认值等等。

假设您的程序需要int参数jdbc_batch_size,默认值为2500,并且可以选择覆盖该值。为此,请按照以下步骤操作

  1. 你创建了自己的类,我们称之为CommandLine
  2. import com.beust.jcommander.Parameter;

    public class CommandLine {
    
     @Parameter(names = "-batchSize", description = "JDBC batch size",required=false)
    
     public int jdbc_batch_size=2500;
    
     }
    
    1. 现在,您在CommandLine cli = new CommandLine();方法
    2. 中创建了上述类main()的对象

      创建指挥官对象JCommander cmdr = new JCommander(cli, args);

      1. 现在,您只需在jdbc_batch_size方法中访问main(),就像
      2. 一样
          

        int jdbc_batch_size = cli.jdbc_batch_size;

        1. 如果您希望override默认值,则通过命令行提供-batchSize 1000
        2. 这简单说明了JComamnder的工作原理。