自寫自看

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

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

          主站蜘蛛池模板: 山阳县| 广灵县| 邵阳县| 山丹县| 长沙县| 福海县| 无为县| 横山县| 金山区| 安化县| 江油市| 桂林市| 夹江县| 时尚| 滦南县| 梅河口市| 嫩江县| 虎林市| 镇原县| 申扎县| 上栗县| 彩票| 长沙县| 娄烦县| 平罗县| 义马市| 乌兰浩特市| 明光市| 武安市| 湖州市| 拉萨市| 定州市| 宝清县| 平原县| 惠东县| 庄浪县| 工布江达县| 岳普湖县| 白河县| 兴城市| 开平市|