Java- 从命令行调用方法

Java- Call a method from the command line

我希望能够通过命令行使用我的应用程序。更具体地说,我想要实现的行为是:

如果我在命令行中输入命令 create 我想调用方法 generateMigrationFile,否则如果我输入的命令是 运行 我想 运行 我的迁移(SpringApplication.run 方法)。我怎样才能做到这一点?

我的应用程序主class

    public static void main(String[] args) {

        //if entered the command run in the command line
        //SpringApplication.run(MigrationsApplication.class, args);

        //if entered the command create in the command line
        MigrationGenerator generator=new MigrationGenerator();
        try {
            generator.generateMigrationFile("TEST");
        } catch (IOException e) {
            System.out.println("There was an error generating the file");
        }

我想这样称呼它:

migrationsApp run

migrationsApp create

您在执行命令行时提供的参数将传递给 args 参数。所以你的代码看起来像:

If (args.length == 0){
  System.exit(-1);
}
if (args[0].equals("run")){
// do run
} else if (args[0].equals("create"){
// do create
}

或者您也可以使用 switch 语句。

您可以使用系统参数,因为您在项目中使用 spring,您可以使用 @Value 注释,例如:

public static void main(String[] args) {

        @Value("${command}")
        final String command;
        switch(command) {
          case "run":
            SpringApplication.run(MigrationsApplication.class, args);
            break;
          case "create":
             MigrationGenerator generator=new MigrationGenerator();
             try {
                generator.generateMigrationFile("TEST");
             } catch (IOException e) {
               System.out.println("There was an error generating the file");
             }
             break;
          default:
            throw new IllegalArgumentException("Command is Invalid");
        }
}

在命令行中将参数作为 --command 传递。如果你是 运行ning jar 使用命令 java -jar --command=运行

所以这是一个展示如何实现它的想法的示例,但请注意,我从不检查确切位置的参数,无用的参数不应破坏应用程序 运行。

您还会注意到,在我的示例中,如果未传递任何参数,它会采用 GUI 模式,这是一种很好的做法,因此如果人们双击您的 .JAR,它就会以 GUI 模式加载。如果这是仅 CLI 应用程序,那么是的,强制一个或多个参数是可以的,但是如果您有 GUI 模式,请使用该模式作为默认模式,除非被用户覆盖。

E.G 预计会工作 java -jar MyApp.jar some crap generate 参数 generate 在那里,应该得到尊重。

public static void main(String[] args) {
        boolean showGui = true;
        boolean generate = false;

        for (String arg : args){
                if(arg.equals("generate")){
                        showGui = false;
                        generate = true;
                }
        }

        //if entered the command run in the command line
        if(showGui){
                SpringApplication.run(MigrationsApplication.class, args);
        }

        //if entered the command create in the command line
        if(generate){
                MigrationGenerator generator=new MigrationGenerator();
                try {
                    generator.generateMigrationFile("TEST");
                } catch (IOException e) {
                    System.out.println("There was an error generating the file");
                }
        }
}

我正在使用 If,因为它是一个只有 1 个自定义参数的简单演示,如果您想支持更多,请将其切换为 switch ... case 语句,但我强烈建议您使用 run 参数不支持,默认为 GUI 模式