我刚刚发现args4j ,来自 commons-cli 的使用非常好!
我正在实现a sub-command handler其中每个子命令都需要访问通过使用所有子命令通用的凭据登录而获得的 session 对象。如果我在主类中创建 session ,子命令将无权访问。我可以在各个子命令中创建 session ,但要做到这一点,我需要访问完整的参数。
/**
* 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;
}
}
}
简而言之,如何创建适用于所有子命令的 session ?
这本身可能不是 args4j 的事情,也许我对子类如何获得正确上下文的思考存在某种类型的设计差距。谢谢!
编辑:我想我可以将 session 对象传递给子类。例如:
action.execute(somesession);
这是最好的方法吗?
最佳答案
我在文档中找到了这个:
- Any Options that you define in the Git class above can parse options that appear prior to the sub-command name. This is useful for defining global options that work across sub-commands.
- The matching sub-command implementation gets instantiated with the default constructor, then a new CmdLineParser will be created to parse its annotations.
这非常酷,所以我想这个想法是传递我在主级别创建的任何新对象,然后注释我需要的其他子命令选项。
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
}
}
关于java - 如何使用 args4j 访问子命令中的主上下文来实现子命令处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27866717/