/**
 * Example code for http://www.brettdaniel.com/archives/2009/01/29/180219/
 */

package sandbox;

import java.lang.reflect.Method;

class Main {

	public static void main(String... args) throws Exception {
		Main instance = new Main();

		CommandExecutor exec = new CommandExecutor();
		// no method defined, executes null method
		exec.runCommand(instance, "asf");
		// define a method to execute
		exec.method = Main.class.getDeclaredMethod(
				"invokedReflectively",
				String.class);
		exec.runCommand(instance, "asf");
	}

	StandardCommand invokedReflectively(String arg) {
		return new StandardCommand();
	}

}

interface ICommand {
	void execute();
}

class StandardCommand implements ICommand {
	public void execute() {
		System.out.println("Executed Standard");
		// do stuff
	}
}

class NullCommand implements ICommand {
	public void execute() {
		System.out.println("Executed Null");
		// do nothing
	}
}

class CommandExecutor {

	public static Method UNDEFINED_METHOD() {
		try {
			return CommandExecutor.class.getDeclaredMethod(
					"UNDEFINED_METHOD_IMPL", String.class);
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException(e);
		}
	}

	public static ICommand UNDEFINED_METHOD_IMPL(String arg) {
		return new NullCommand();
	}

	Method method = UNDEFINED_METHOD();

	void runCommand(Object instance, String arg) throws Exception {
		ICommand command = (ICommand) method.invoke(instance, arg);
		command.execute();
	}
}

