zoukankan      html  css  js  c++  java
  • 反射四(动态代理)

    1.动态代理

    (1)Proxy提供用于创建动态代理类和代理对象的静态方法,它是所有动态代理类的父亲

    (2)Proxy提供了两个方法来创建动态代理类和动态代理实例

    2.使用动态代理实现AOP(面向切面编程)

    代理设计模式的原理:使用一个代理将对象包装起来,然后用该代理对象取代原始对象,任何对原始对象的调用都要通过代理。代理对象决定是否以及何时将方法调用转到原始对象上。

    3.实现

    
    
    /**
    * 动态代理
    */
    @Test
    public void testProxy(){

    final ArithmeticCalculator arithmeticCalculator = new ArithmeticCalculatorImpl();//final防止该对象被提前回收
    /**
    * Proxy.newProxyInstance(classLoader,Class<?>[],InvocationHandler
    * classLoader由动态代理产生的对象由那个类加载其加载,通常情况下和被代理对象使用一样的类加载器
    * Class<?>[]:由动态代理产生的对象必须需要实现的接口的Class数组,数组中必须是接口对应的class
    * InvocationHandler:当具体调用代理对象的方法时,将产生什么行为
    */

    ArithmeticCalculator proxy = (ArithmeticCalculator) Proxy.newProxyInstance(arithmeticCalculator.getClass().getClassLoader(), new Class[]{ArithmeticCalculator.class}, new InvocationHandler() {
    /**
    *
    * @param proxy
    * @param method:正在被调用的方法
    * @param args:调用方法传入的参数
    * @return
    * @throws Throwable
    */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    //调用被代理的目标方法,真正执行目标方法
    System.out.println("方法执行前操作");
    Object result = method.invoke(arithmeticCalculator,args);
    System.out.println("方法执行后操作");
    return result;
    }
    });
    //调用的是上边的invoke方法
    int result = proxy.add(2,5);
    System.out.println(result);
    result = proxy.mul(1,2);
    System.out.print(result);
    }
    
    
    /**
    * 接口定义,接口实现省略
    */
    public interface ArithmeticCalculator {
    int add(int i,int j);
    int sub(int i,int j);
    int mul(int i,int j);
    int div(int i,int j);
    }

    
    

    4.代码调用

  • 相关阅读:
    (精华)将json数组和对象转换成List和Map(小龙哥和牛徳鹤的对话)
    优先队列底层实现是堆(heap)(操作系统进程调度)
    (透彻理解)最精锐代码::堆的三种基本操作新建-插入-删除
    (考研)读者写者问题(附代码)
    (考研)黑电吃苹果同步互斥问题(附代码)
    (考研)哲学家进餐问题(附代码)
    (考研)吸烟者问题(赋代码)
    (考研)PV操作和信号量
    01.第一章_C++ Primer学习笔记_开始
    C++学习笔记
  • 原文地址:https://www.cnblogs.com/yxqing/p/10605777.html
Copyright © 2011-2022 走看看