• 动态代理


     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 }
  • 相关阅读:
    Web前端工程师技能列表
    CSS框架的相关汇总(CSS Frameworks)
    一个有趣的发现
    (转丁学)Firefox2的一个bug和脑子进了水的IE
    深入语义:列表Tag(ul/ol)和表格Tag(table)的抉择
    css命名简单框架
    腾讯的三栏布局考题
    土豆网前端概况
    伪绝对定位(译)
    右下角浮动广告代码DEMO
  • 原文地址:https://www.cnblogs.com/cowshed/p/11397682.html
Copyright © 2020-2023  润新知