2017-04-13 30 views
0

對於每個命令我都有一個具體的類來實現某個接口。 例如:如何設置命令的描述,但不是選項

public class FooCommand implements Command{ 

    @Parameter(names = {"-?","--help"}, description = "display this help",help = true) 
    private boolean helpRequested = false; 
    ... 
} 

這是用法消息我得到:

Usage: foo-command [options] 
    Options: 
    -?, --help 
     display this help 

我如何添加描述命令(而不是選擇)。例如,我想這樣的用法消息:

Usage: foo-command [options] - This command is used as base foo 
    Options: 
    -?, --help 
     display this help 

編輯我有foo的命令,噓命令,拉拉命令。然而,所有這些命令是分開的,不在一個主命令內(換句話說,這不像git克隆...)。 這是我得到的使用

JCommander jCommander=new JCommander(command, args); 
jCommander.setProgramName(commandName);//for example foo-command 
StringBuilder builder=new StringBuilder(); 
jCommander.usage(builder); 

回答

2

下面的代碼片段可能是你正在尋找一個起點的方式。

@Parameters(commandDescription = "foo-command short description") 
public class FooCommand implements Command { 

    @Parameter(names = {"-?", "--help"}, description = "display this help", 
     help = true) 
    private boolean helpRequested = false; 

    @Parameter(description = "This command is used as base foo") 
    public List<String> commandOptions; 

    // your command code goes below 
} 


public class CommandMain { 

    public static void main(String[] args) { 
     JCommander jc = new JCommander(); 
     jc.setProgramName(CommandMain.class.getSimpleName()); 
     FooCommand foo = new FooCommand(); 
     jc.addCommand("foo-command", foo); 
     // display the help 
     jc.usage(); 
    } 
} 

輸出

Usage: CommandMain [options] [command] [command options] 
    Commands: 
    foo-command  foo-command short description 
     Usage: foo-command [options] This command is used as base foo 
     Options: 
      -?, --help 
      display this help 
      Default: false 

也看看:JCommander command syntax

編輯顯示的命令本身的描述。在這種情況下,類FooCommand上的註釋@Parameters(commandDescription = "foo-command short description")可以省略。

Command command = new FooCommand(); 
JCommander jc = new JCommander(command, args); 
jc.setProgramName("foo-command"); 
StringBuilder builder = new StringBuilder(); 
jc.usage(builder); 
System.out.println(builder); 

輸出

Usage: foo-command [options] This command is used as base foo 
    Options: 
    -?, --help 
     display this help 
     Default: false 
+0

謝謝您的回答。但我不需要CommandMain。我有不同的命令沒有「主」 –

+0

@Pavel命令主要是提供[MCVE](http://stackoverflow.com/help/mcve)。也許你應該在你的問題中提供一個更好的代碼示例。 – SubOptimal

+0

請參閱我的編輯。 –