LoginSignup
12
13

More than 5 years have passed since last update.

args4j でサブコマンドを使う

Last updated at Posted at 2015-08-04

git みたいなコマンドライン引数の体系にしたい場合、結構簡単に args4j で書ける。

サブコマンド
/**
 * args4j でサブコマンドを使う
 */
public class SubCommandSample {

    /**
     * 引数によって実行するオブジェクトを切り替える
     */
    @Argument(handler = SubCommandHandler.class)
    @SubCommands({
        @SubCommand(name = "hello", impl = HelloCommand.class),
        @SubCommand(name = "goodbye", impl = GoodbyeCommand.class)
    })
    private Command command;

    public static void main(String[] args) throws CmdLineException {
        SubCommandSample subcommand = new SubCommandSample();
        new CmdLineParser(subcommand).parseArgument(args);
        subcommand.command.execute();
    }

    /**
     * コマンド
     */
    public static interface Command {
        public void execute();
    }

    /**
     * こんにちは
     */
    public static class HelloCommand implements Command {
        @Override
        public void execute() {
            System.out.println("Hello");
        }
    }

    /**
     * さようなら
     */
    public static class GoodbyeCommand implements Command {
        @Override
        public void execute() {
            System.out.println("Goodbye");
        }
    }
}
実行
public class SubCommandSampleTest {

    @Test
    public void main() throws CmdLineException {
        SubCommandSample.main(new String[] { "hello" }); // Hello
        SubCommandSample.main(new String[] { "goodbye" }); // Goodbye
        SubCommandSample.main(new String[] { "aaa" }); // エラー
    }
}

引数に渡された文字列で if 文分岐するよりは、これを使うと、自然とコマンドパターンになるので、見やすいし、書きやすいと思う。

12
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13