我刚发现args4j,很高兴使用来自commons-cli!
我正在实现a sub-command handler,其中每个子命令都需要访问通过使用所有子命令共有的凭证登录获得的会话对象。如果我在主类中创建会话,子命令将无法访问。我可以在各个子命令中创建会话,但为了做到这一点,我需要访问完整的参数。
/**
* Sample program from args4j site (modified)
* @author
* Kohsuke Kawaguchi (kk@kohsuke.org)
*/
public class SampleMain {
// needed by all subcommands
Session somesession;
@Option(name="-u",usage="user")
private String user = "notsetyet";
@Option(name="-p",usage="passwd")
private String passwd = "notsetyet";
@Argument(required=true,index=0,metaVar="action",usage="subcommands, e.g., {search|modify|delete}",handler=SubCommandHandler.class)
@SubCommands({
@SubCommand(name="search",impl=SearchSubcommand.class),
@SubCommand(name="delete",impl=DeleteSubcommand.class),
})
protected Subcommand action;
public void doMain(String[] args) throws IOException {
CmdLineParser parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
// here I want to do my things in the subclasses
// but how will the subcommands get either:
// a) the session object (which I could create in this main class), or
// b) the options from the main command in order to create their own session obj
action.execute();
} catch( CmdLineException e ) {
System.err.println(e.getMessage());
return;
}
}
}
简而言之,如何创建适用于所有子命令的会话?
它本身可能不是一个args4j的东西,也许我的想法中存在某种类型的设计缺口,关于子类如何获得正确的上下文。谢谢!
编辑:我想我可以将会话对象传递给子类。 E.g:action.execute(somesession);
这是最好的方法吗?
答案 0 :(得分:1)
我在文档中找到了这个:
- 您在上面的Git类中定义的任何选项都可以解析子命令名称之前出现的选项。这对于定义跨子命令工作的全局选项非常有用。
- 匹配的子命令实现使用默认构造函数实例化,然后将创建一个新的CmdLineParser来解析其注释。
这很酷,所以我想这个想法是传递我在主级别创建的任何新对象,然后注释我需要的其他子命令选项。
public class DeleteCommand extends SubCommand {
private Session somesession;
@Option(name="-id",usage="ID to delete")
private String id = "setme";
public void execute(Session asession) {
somesession = asession;
// do my stuff
}
}