2017-04-13 43 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

请参阅我的编辑。 –