2015-01-09 26 views
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); 

這是最好的方法嗎?

回答

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 
    } 
}