public class TestReflectCommand {
public static void main(String[] args){
CommandLoader cl=new DefaultCommandLoader(new DefaultShowCommand());
cl.excute("executeShowList",null);
}
}
public interface CommandLoader {
void excute(String commandName,Object[] argument);
}
public class DefaultCommandLoader implements CommandLoader {
private ShowCommand showCommand;
private HashMap subCommandMap=new HashMap();
public DefaultCommandLoader(ShowCommand showCommand){
this.showCommand=showCommand;
init();
}
private void init() {
Method[] allMethod=this.showCommand.getClass().getMethods();
for(int i=0;i<allMethod.length;i++){
Method m=allMethod
;
if(m.getName().startsWith("execute")){
subCommandMap.put(m.getName(), m);
}
}
}
public void excute(String commandName, Object[] argument) {
Method m=(Method) this.subCommandMap.get(commandName);
if(m==null){
throw new NullPointerException("not found command");
}
try{
m.invoke(this.showCommand,argument);
}
catch(Exception e){
throw new RuntimeException("Load command["+m.getName()+"error");
}
}
}
public interface ShowCommand {
public void executeShowList();
public void excuteShowString();
public void executeShowInteger();
public void executeShowLong();
}
public class DefaultShowCommand implements ShowCommand {
public void excuteShowString() {
System.out.println(String.class.getName());
}
public void executeShowInteger() {
System.out.println(Integer.class.getName());
}
public void executeShowList() {
System.out.println(List.class.getName());
}
public void executeShowLong() {
System.out.println(Long.class.getName());
}
}