java學習

          java學習

           

          Java的動態(tài)代理例子

          Java的動態(tài)代理是為了攔截目標方法,例子:
          public interface Person {
          String sing(String name);
          String dance(String name);
          }
          public class Liyuchun implements Person {
          public String sing(String name){
          System.out.println("唱" + name +"歌");
          return "唱" + name +"歌";
          }
          public String dance(String name){
          System.out.println("跳"+name+"舞");
          return "跳"+name+"舞";
          }
          }
          public class LiyuchunProxy {
          private Person person ;
          public Person createProxy(Person p){
          this.person=p;
          return (Person) Proxy.newProxyInstance(LiyuchunProxy.class.getClassLoader(), person.getClass().getInterfaces(), new InvocationHandler(){
          public Object invoke(Object proxy, Method method, Object[] args)
          throws Throwable {
          String methodName = method.getName();
          if(methodName.equals("sing")){
          return method.invoke(person, args);
          }else if(methodName.equals("dance")){
          return method.invoke(person, args);
          }else{
          System.out.println("不支持");
          return null;
          }
          }
          });
          }
          }
          public class ProxyTest {
          public static void main(String[] args) {
          Liyuchun cun = new Liyuchun();
          LiyuchunProxy liyuchunProxy = new LiyuchunProxy();
          Person person = liyuchunProxy.createProxy(cun);
          String result =  person.dance("機械");
          System.out.println(result);
          }
          }

          posted on 2017-08-16 17:06 楊軍威 閱讀(94) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導航:
           

          導航

          統(tǒng)計

          常用鏈接

          留言簿

          隨筆檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 昭平县| 云霄县| 定安县| 桂平市| 宁强县| 莒南县| 黑龙江省| 南宫市| 麻城市| 广平县| 甘南县| 绩溪县| 建宁县| 光山县| 江北区| 资阳市| 阿瓦提县| 西城区| 敖汉旗| 贡山| 华蓥市| 石嘴山市| 谢通门县| 汉川市| 烟台市| 柳河县| 仁布县| 桑植县| 兰西县| 呼图壁县| 临澧县| 松江区| 洛南县| 海盐县| 绵竹市| 时尚| 徐州市| 鱼台县| 都江堰市| 长武县| 南京市|