1 回答

TA貢獻1757條經驗 獲得超8個贊
main對于@Command作為入口點的每個方法都有一個單獨的方法是完全沒問題的。main需要該方法,以便可以從命令行獨立調用該命令。
例如:
@Command(name = "hello")
class Hello implements Runnable {
public static void main(String[] args) {
CommandLine.run(new Hello(), args);
}
public void run() { System.out.println("hello"); }
}
@Command(name = "bye")
class Bye implements Runnable {
public static void main(String[] args) {
CommandLine.run(new Bye(), args);
}
public void run() { System.out.println("bye"); }
}
一種例外情況是當您的應用程序具有帶有子命令的命令時。在這種情況下,您只需要main為頂級命令提供方法,而不需要為子命令提供方法。
帶有子命令的示例:
@Command(name = "git", subcommands = {Commit.class, Status.class})
class Git implements Runnable {
public static void main(String[] args) { // top-level command needs main
CommandLine.run(new Git(), args);
}
public void run() { System.out.println("Specify a subcommand"); }
}
@Command(name = "commit")
class Commit implements Runnable {
@Option(names = "-m") String message;
@Parameters File[] files;
public void run() {
System.out.printf("Committing %s with message '%s'%n",
Arrays.toString(files), message);
}
}
@Command(name = "status")
class Status implements Runnable {
public void run() { System.out.println("All ok."); }
}
注意,main當有子命令時,只有頂級命令需要一個方法。即使使用子命令,也不需要工廠。
添加回答
舉報