当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
java动态代理DynamicProxy
发布时间:2010/12/4 22:59:41 来源:城市学习网 编辑:ziteng
  1.被代理对象的接口:
  1 package test.dynamicproxy;
  2
  3 public interface TargetInterface {
  4     public void SayHello();
  5     public int sum(int a ,int b);
  6 }
  2.被代理的对象:
  01 package test.dynamicproxy;
  02
  03 public class Target implements TargetInterface {
  04
  05     public void SayHello(){
  06         System.out.println("Hello");
  07     }
  08     public int sum(int a, int b) {
  09         return a+b;
  10     }
  11 }
  3.InvocationHandler包装:
  01 package test.dynamicproxy;
  02
  03 import java.lang.reflect.InvocationHandler;
  04 import java.lang.reflect.Method;
  05
  06 public class TargetInvocationHandler implements InvocationHandler {
  07
  08     private Object object;
  09     public TargetInvocationHandler(Object obj){
  10         this.object=obj;
  11     }
  12
  13     public Object invoke(Object proxy, Method method, Object[] args2)
  14     throws Throwable
  15     {
  16         doBefore();
  17         Object result = method.invoke(object, args2);
  18         doAfter();
  19         return result;
  20     }
  21
  22     public void doBefore(){
  23         System.out.println("do before");
  24     }
  25
  26     public void doAfter(){
  27         System.out.println("do after");
  28     }
  29 }
  4.测试类:
  01 package test.dynamicproxy;
  02
  03 import java.lang.reflect.Proxy;
  04
  05 public class TestDynamicProxy {
  06
  07     /**
  08      * @param args
  09      */
  10     public static void main(String[] args) {
  11         Target t=new Target();
  12         TargetInvocationHandler handler=new TargetInvocationHandler(t);
  13
  14         TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(
  15                 t.getClass().getClassLoader(),
  16                 t.getClass().getInterfaces(),
  17                 handler);
  18
  19         proxy.SayHello();
  20
  21         int b=proxy.sum(10, 20);
  22         System.out.println(b);
  23     }
  24
  25 }
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved