引用:http://www.blogjava.net/thisliy/archive/2009/10/24/299621.html
1.真实对象接口
1 public interface IAnimal { 2 void info(); 3 }2.真实类
1 public class Cat implements IAnimal{ 2 3 public void info() { 4 System.out.println( " This is a cat! " ); 5 } 6 7 }3.调用处理器
1 import java.lang.reflect.InvocationHandler; 2 import java.lang.reflect.Method; 3 4 public class TraceHandler implements InvocationHandler{ 5 6 private Object target; // 以真实角色作为代理角色的属性 7 8 // 构造器 9 public TraceHandler(Object target) { 10 this .target = target; 11 } 12 13 /* 14 * 通过反射机制动态执行真实角色的每一个方法 15 */ 16 public Object invoke(Object proxy, Method method, Object[] args) 17 throws Throwable { 18 try { 19 System.out.println( " 被拦截的方法: " + method.getName()); 20 System.out.println( " 预处理. " ); 21 22 return method.invoke(target, args); // 调用真是对象的method方法 23 24 } catch (Exception e) { 25 return null ; 26 } finally { 27 System.out.println( " 善后处理. " ); 28 } 29 } 30 }4.客户端
1 import java.lang.reflect.InvocationHandler; 2 import java.lang.reflect.Proxy; 3 4 public class ProxyTest { 5 public static void main(String[] args) { 6 7 // 真实对象(即被代理对象) 8 final IAnimal animal = new Cat(); 9 10 // 为真实对象制定一个调用处理器 11 InvocationHandler handler = new TraceHandler(animal); 12 13 // 获得真实对象(animal)的一个代理类 ★★★★★ 14 Object proxyObj = Proxy.newProxyInstance( 15 animal.getClass().getClassLoader(), // 真实对象的类加载器 16 animal.getClass().getInterfaces(), // 真实对象实现的所有接口 17 handler // 真实对象的处理器 18 ); 19 20 if (proxyObj instanceof IAnimal) { 21 System.out.println( " the proxyObj is an animal! " ); 22 23 IAnimal animalProxy = (IAnimal)proxyObj; // proxyObj与animal都实现了IAnimal接口 24 25 animalProxy.info(); // 像普通animal对象一样使用(通过handler的invoke方法执行) 26 } else { 27 System.out.println( " the proxyObj isn't an animal! " ); 28 } 29 } 30 }
结果:
the proxyObj is an animal!被拦截的方法:info预处理.This is a cat!善后处理.