有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么picocli不能从命令行识别我的选项?

我正在尝试使用PICOCLI在Java中构建CLI,但我停留在一个非常基本的点上。我根本无法让我的应用程序给消费者一个选项和它的价值。这是我的班级:

package com.example.demo;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import picocli.CommandLine;

@SpringBootApplication

@CommandLine.Command(name = "Greet", header = "%n@|green Hello world demo|@")
class DemoApplication implements Runnable {

    @CommandLine.Option(names = {"-u", "--user"}, required = true, description = "The user name.")
    String userName;

    public void run() {
        System.out.println("Hello, " + userName);
    }

    public static void main(String... args) {
        CommandLine.run(new DemoApplication(), System.err, args);
    }
}

然后我做了一个mvn packagecd targetjava -jar demo-1.0.jar Greet -u pico但我只遇到了以下情况:

Unmatched argument at index 0: 'Greet'

Hello world demo
Usage: Greet -u=<userName>
  -u, --user=<userName>   The user name.

我已经没有耐心打印一条简单的消息了!我不知道如何解决这个问题。请帮忙


共 (1) 个答案

  1. # 1 楼答案

    如果使用java调用命令,则无需指定命令名Greet,只需指定命令行选项:

    java -jar demo-1.0.jar -u pico
    

    你可以这样想:java -jar demo-1.0.jarGreet命令

    您可能希望使用Application Assembler Maven Plugin来创建一个启动程序脚本,并将该启动程序脚本命名为Greet

    这样,程序的用户就可以通过以下命令在命令行上调用它:

    Greet -u pico
    

    AppAssembler的maven配置应如下所示:

    <project>
      ...
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>appassembler-maven-plugin</artifactId>
            <version>1.10</version>
            <configuration>
              <programs>
                <program>
                  <mainClass>com.example.demo.DemoApplication</mainClass>
                  <id>Greet</id>
                </program>
              </programs>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    

    更新:我在用户手册中添加了一个关于how to run picocli-based applications的部分


    更新2:我建议升级到picocli的最新版本;版本4.0引入了一个新的execute API,它更好地支持退出代码和错误处理

    在你的例子中,这看起来是这样的:

    
    public static void main(String... args) {
      int exitCode = new CommandLine(new DemoApplication()).execute(args);
      System.exit(exitCode);
    }