定义被代理对象的接口和接口实现:
1 package com.xl; 2 public interface Book { 3 4 public void addBooks(); 5 }
1 package com.xl; 2 3 public class BookImpl implements Book { 4 5 @Override 6 public void addBooks() { 7 // TODO Auto-generated method stub 8 System.out.println("the books add successfully!"); 9 10 } 11 12 }
定义代理器,实现InvocationHandler接口,定义私有变量和相应的构造函数,重写invoke方法,调用method对象的invoke方法,返回被代理对象:
1 package com.xl; 2 import java.lang.reflect.InvocationHandler; 3 import java.lang.reflect.Method; 4 5 6 public class bookproxy implements InvocationHandler { 7 8 private Object o; 9 10 //构造函数 11 public bookproxy(Object o){ 12 this.o = o; 13 } 14 @Override 15 public Object invoke(Object proxy, Method method, Object[] args) 16 throws Throwable { 17 18 Object rs; 19 20 System.out.println("方法调用前!"); 21 22 rs = method.invoke(o); 23 24 System.out.println("方法调用后!"); 25 26 return rs; 27 } 28 29 }
客户端的调用,创建被代理对象的实例给其接口来引用,创建代理器并将被代理对象传进去,给InvocationHandler来引用,创建代理对象实例,强制转换成被代理接口,最后调用代理对象实例的方法:
1 package com.xl; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Proxy; 5 6 public class ProxyTest { 7 8 /** 9 * @param args 10 */ 11 public static void main(String[] args) { 12 // TODO Auto-generated method stub 13 14 Book b = new BookImpl(); 15 16 InvocationHandler ih = new bookproxy(b); 17 18 Book bproxy = (Book) Proxy.newProxyInstance(b.getClass().getClassLoader(), 19 b.getClass().getInterfaces(), 20 ih); 21 22 bproxy.addBooks(); 23 } 24 25 }
动态代理的实现过程
时间: 2024-10-10 08:21:53