zoukankan      html  css  js  c++  java
  • java 动态代理 Proxy.newProxyInstance 使用心法

    使用JDk的Proxy类的静态方法newProxyInstance ,让JVM自动生成一个新的类,类中包含了inerfaces参数中的所有方法,每个方法都调用h.invoke 方法
     
     
     
    AOP 动态代理
     
    package com.atguigu.spring.aop;
     
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    import java.util.Arrays;
     
    //代理类
    public class ArithmeticCalculatorLoggingProxy {
     
    //1.被代理的对象 目标对象
    private ArithmeticCalculator target ; // 实际上是ArithmeticCalculatorImpl对象.
     
    //通过构造器的方式将目标对象传入
    public ArithmeticCalculatorLoggingProxy(ArithmeticCalculator target){
    this.target = target ;
    }
     
    //获取代理对象
    public ArithmeticCalculator getLoggingProxy(){
    //定义代理对象
    ArithmeticCalculator proxy ;
     
    /**
    * loader: ClassLoader 类加载器
    * interfaces: 目标类的所有接口,目的是获取接口中的方法
    * h: InvocationHandler
    */
    ClassLoader loader = target.getClass().getClassLoader();
    Class[] interfaces = target.getClass().getInterfaces();
    InvocationHandler h = new InvocationHandler() {
    /**
    * proxy:代理对象 在invoke方法中一般不会用
    * method:正在调用的方法
    * args:调用方法传入的参数
    */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable {
    String methodName = method.getName();
    //加日志
    System.out.println("ATGUIGU===>The method "+methodName+" begins with "+ Arrays.asList(args));
    //执行目标方法
    Object result = method.invoke(target, args);
    //加日志
    System.out.println("ATGUIGU===>The method "+methodName+" ends with " + result );
    return result;
    }
    };
     
    proxy = (ArithmeticCalculator)Proxy.newProxyInstance(loader, interfaces, h);
     
     
    使用JDk的Proxy的静态方法newProxyInstance ,让JVM自动生成一个新的类,类中包含了inerfaces参数中的所有方法,每个方法都调用h.invoke 方法
    return proxy ;
    }
     
     
    }
     
  • 相关阅读:
    ios中的任务分段
    UVA 531
    OGG同构(ORACLE-ORACLE)、异构(ORACLE-MYSQL)同步配置及错误解析
    JavaScript自调用匿名函数
    Redis 主从配置和参数详解
    python开发环境设置(windows)
    Havel-Hakimi定理 hdu2454 / poj1695 Havel-Hakimi定理
    libevent源码分析-介绍、安装、使用
    Linux网络监控工具nethogs
    spring(3)------控制反转(IOC)/依赖注入(DI)
  • 原文地址:https://www.cnblogs.com/jiangtao1218/p/11862907.html
Copyright © 2011-2022 走看看