我刚刚发现了args4j,来自 commons-cli 的使用非常好!
我正在实现一个子命令处理程序,其中每个子命令都需要访问通过使用所有子命令通用的凭据登录而获得的会话对象。如果我在主类中创建会话,则子命令将无权访问。我可以在各个子命令中创建会话,但要做到这一点,我需要访问完整的参数。
/**
* 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 的事情,也许在我关于子类如何获得正确上下文的想法中存在某种类型的设计差距。谢谢!
编辑:我想我可以将会话对象传递给子类。例如:
action.execute(somesession);
这是最好的方法吗?