自写自看

利用方法名称执行方法行为的源代码

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());
}

}

posted on 2008-02-25 11:48 昨夜人生 阅读(179) 评论(0)  编辑  收藏 所属分类: 其他


只有注册用户登录后才能发表评论。


网站导航: