1 分为jdk自带代理
2 实现接口 InvocationHandler ,用反射调用方法
3 获取代理类:Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(), new TestProxy(obj));
4
5 实例:
6 public interface ReadFile {
7 public void read();
8 }
9
10 public class Boss implements ReadFile {
11 @Override
12 public void read() {
13 System.out.println("I'm reading files.");
14 }
15 }
16
17 public class Secretary implements InvocationHandler {
18 private Object object;
19 public Secretary(Object object) {
20 this.object = object;
21 }
22 @Override
23 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
24 System.out.println("I'm secretary.");
25 Object result = method.invoke(object, args);
26 return result;
27 }
28 }
29
30 public class Main {
31 public static void main(String[] args) {
32 ReadFile boss = new Boss();
33 InvocationHandler handler = new Secretary(boss);
34 ReadFile secretary = (ReadFile) Proxy.newProxyInstance(
35 boss.getClass().getClassLoader(),
36 boss.getClass().getInterfaces(),
37 handler);
38 secretary.read();
39 }
40 }
41
42
43
44 CGLIB具有简单易用,它的运行速度要远远快于JDK的Proxy动态代理:
45 public class CglibProxy implements MethodInterceptor {
46 @Override
47 public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
48 System.out.println("++++++before " + methodProxy.getSuperName() + "++++++");
49 System.out.println(method.getName());
50 Object o1 = methodProxy.invokeSuper(o, args);
51 System.out.println("++++++before " + methodProxy.getSuperName() + "++++++");
52 return o1;
53 }
54 }
55 public class Main2 {
56 public static void main(String[] args) {
57 CglibProxy cglibProxy = new CglibProxy();
58
59 Enhancer enhancer = new Enhancer();
60 enhancer.setSuperclass(UserServiceImpl.class);
61 enhancer.setCallback(cglibProxy);
62
63 UserService o = (UserService)enhancer.create();
64 o.getName(1);
65 o.getAge(1);
66 }
67 }