java - 如何使用 args4j 访问子命令中的主上下文来实现子命令处理程序?

标签 java design-patterns command-line-arguments args4j

我刚刚发现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/

相关文章:

java - 不同类数组单例实例中 Find And Delete 方法中数组的全局索引

c++ - 处理无法实例化自身的对象的最佳方法?

C++:模式:哪种模式适合特定的代码执行取决于命令行参数

javascript - 为什么, Hook 到对象的函数中的默认上下文不是它本身

bash - 如何复制 bash 脚本的参数以进行单独处理?

c# - 按需输出使用 DragonFruit 的帮助

shell - 如何使用 grpc_cli 传递元数据?

java - 将值放入输入字段中,即来自 servlet 的 html 表单中的文本框中

java - 如何使用 JNI 创建 native 类?

java - 如何将运行者中的数字列表设置为构造函数中的 ArrayList?