args4j でサブコマンドを使う

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 文分岐するよりは、これを使うと、自然とコマンドパターンになるので、見やすいし、書きやすいと思う。