自寫自看

          利用方法名稱執行方法行為的源代碼

          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 昨夜人生 閱讀(192) 評論(0)  編輯  收藏 所屬分類: 其他

          主站蜘蛛池模板: 曲阳县| 衡阳县| 深水埗区| 盱眙县| 芷江| 高邑县| 嘉祥县| 古田县| 万载县| 宝山区| 固安县| 旺苍县| 株洲县| 德兴市| 南宫市| 武强县| 伽师县| 日照市| 涿州市| 新龙县| 永康市| 布尔津县| 林周县| 姜堰市| 宁强县| 漠河县| 芒康县| 台北县| 海阳市| 修文县| 中宁县| 昆山市| 新宁县| 湾仔区| 阿荣旗| 涿鹿县| 武乡县| 五峰| 南投市| 楚雄市| 宜良县|