0
我剛剛發現args4j,所以很高興使用來自commons-cli!如何訪問使用args4j實現子命令處理程序的子命令中的主要上下文?
我正在實施a sub-command handler,其中每個子命令都需要訪問通過使用所有子命令共有的憑據登錄而獲得的會話對象。如果我在主類中創建會話,則子命令將無法訪問。我可以在單個子命令中創建會話,但要做到這一點,我需要訪問完整的參數。
/**
* Sample program from args4j site (modified)
* @author
* Kohsuke Kawaguchi ([email protected])
*/
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);
這是最好的方法嗎?