Java程序接收参数的几种方法

xiaozhch5 编程语言

使用common-cli包

解析参数

    public static CommandLine parseArgs(String[] args) throws ParseException {
        CommandLineParser commandLineParser = new DefaultParser();
        Options options = new Options();
        options.addOption("f","sqlFilePath", true, "sql文件路径");
        options.addOption("m", "mode", true, "flink运行模式,batch/streaming");
        return commandLineParser.parse(options, args);
    }


获取参数

        CommandLine commandLine = parseArgs(args);
        String sqlFilePath;
        if (commandLine.hasOption("f")) {
            sqlFilePath = commandLine.getOptionValue("f");
        }
        else {
            throw new Exception("请指定sql文件路径, -f xxx.sql");
        }


使用jcommander包

定义参数类

public class FlinkCompactionConfig {
    @Parameter(names = {"--help", "-h"}, help = true)
    public Boolean help = false;

    // ------------------------------------------------------------------------
    //  Hudi Write Options
    // ------------------------------------------------------------------------

    @Parameter(names = {"--path"}, description = "Base path for the target hoodie table.", required = true)
    public String path;
}    


参数类解析

  public static FlinkCompactionConfig getFlinkCompactionConfig(String[] args) {
    FlinkCompactionConfig cfg = new FlinkCompactionConfig();
    JCommander cmd = new JCommander(cfg, null, args);
    if (cfg.help || args.length == 0) {
      cmd.usage();
      System.exit(1);
    }
    return cfg;
  }


参数使用

String path = cfg.path;


回复

我来回复
  • 暂无回复内容