1 import java.lang.reflect.InvocationHandler;
2 import java.lang.reflect.Method;
3 import java.lang.reflect.Proxy;
4
5 //动态代理的使用,体会反射是动态语言的关键
6 interface Subject {
7 void action();
8 }
9
10 // 被代理类
11 class RealSubject implements Subject {
12 public void action() {
13 System.out.println("我是被代理类,记得要执行我哦!么么~~");
14 }
15 }
16
17 class MyInvocationHandler implements InvocationHandler {
18 Object obj;// 实现了接口的被代理类的对象的声明
19
20 // ①给被代理的对象实例化②返回一个代理类的对象
21 public Object blind(Object obj) {
22 this.obj = obj;
23 return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
24 .getClass().getInterfaces(), this);
25 }
26 //当通过代理类的对象发起对被重写的方法的调用时,都会转换为对如下的invoke方法的调用
27 @Override
28 public Object invoke(Object proxy, Method method, Object[] args)
29 throws Throwable {
30 //method方法的返回值时returnVal
31 Object returnVal = method.invoke(obj, args);
32 return returnVal;
33 }
34
35 }
36
37 public class TestProxy {
38 public static void main(String[] args) {
39
40 //1.被代理类的对象
41 RealSubject real = new RealSubject();
42 //2.创建一个实现了InvacationHandler接口的类的对象
43 MyInvocationHandler handler = new MyInvocationHandler();
44 //3.调用blind()方法,动态的返回一个同样实现了real所在类实现的接口Subject的代理类的对象。
45 Object obj = handler.blind(real);
46 Subject sub = (Subject)obj;//此时sub就是代理类的对象
47
48 sub.action();//转到对InvacationHandler接口的实现类的invoke()方法的调用
49
50 //再举一例
51 NikeClothFactory nike = new NikeClothFactory();
52 ClothFactory proxyCloth = (ClothFactory)handler.blind(nike);//proxyCloth即为代理类的对象
53 proxyCloth.productCloth();
54
55
56
57 }
58 }