本文参考

在上一篇"Netty + Spring + ZooKeeper搭建轻量级RPC框架"文章中涉及到了Java动态代理和CGLib代理,在这篇文章中对这两种代理方式做详解

下面是本文参考:

https://www.baeldung.com/cglib

https://blog.csdn.net/shallynever/article/details/103351299

https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Proxy.html

环境

Oracle jdk 1.8.0_241 + CGLib 3.3.0

Java动态代理 —— 简单案例

首先声明一个接口

public interface FooInterface {

  String sayHello();
}

然后实现这个接口

public class FooImpl implements FooInterface {

  @Override

  public String sayHello() {

    return "hello world!";
  }
}

最后是Java动态代理的实现

@Test
public void helloProxy() {

  FooInterface foo = (FooInterface) Proxy.newProxyInstance(

    FooInterface.class.getClassLoader(),

    new Class<?>[]{FooInterface.class},

    new InvocationHandler() {

      @Override

      public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("proxy invoked");

        return method.invoke(new FooImpl(), args);
      }
    }
  );

  System.out.println(foo.sayHello());
}

还有另外一种分步的写法,上面单步写法的newProxyInstance()方法实际上是将分步写法的代码统一到了一起,并且已经在方法内捕获了异常

a proxy instance can be also be created by calling the Proxy.newProxyInstance method, which combines the actions of calling Proxy.getProxyClass with invoking the constructor with an invocation handler.

但是分步写法能够帮助我们更好地理解Java动态代理

@Test
public void helloProxy() throws NoSuchMethodException, IllegalAccessException,

InvocationTargetException, InstantiationException {

  Class<?> proxyClass = Proxy.getProxyClass(

    FooInterface.class.getClassLoader(),

    FooInterface.class);

  InvocationHandler handler = new InvocationHandler() {

    @Override

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

      System.out.println("proxy invoked");

      return method.invoke(new FooImpl(), args);
    }
  };

  FooInterface foo = (FooInterface) proxyClass.getConstructor(InvocationHandler.class)
                                          .newInstance(handler);

  System.out.println(foo.sayHello());
}

执行结果如下

Java动态代理 —— 基本概念

动态代理类 -> 在运行时创建,并实现了一系列指定的接口,对应分步写法中Proxy.getProxyClass()方法获得的proxyClass实例

A dynamic proxy class (simply referred to as a proxy class below) is a class that implements a list of interfaces specified at runtime when the class is created

代理接口 -> 由动态代理类实现的接口,对应Proxy.getProxyClass()方法内指明的FooInterface

A proxy interface is such an interface that is implemented by a proxy class.

代理实例 -> 动态代理类创建的实例,对应分步写法中proxyClass.getConstructor(InvocationHandler.class).newInstance()方法返回的对象,并且该对象可以被强制类型转换为代理接口的实例,即分步写法中的foo

每一个代理实例都有一个相关联的InvocationHandler实现,并且代理实例的方法调用会经过InvocationHandler的invoke方法,我们可以看到在输出"hello world!"之前先输出了"proxy invoke",说明经过了invoke()方法

A proxy instance is an instance of a proxy class. Each proxy instance has an associated invocation handler object, which implements the interface InvocationHandler.

A method invocation on a proxy instance through one of its proxy interfaces will be dispatched to the invoke method of the instance's invocation handler, passing the proxy instance

invoke() -> 第一个参数Object proxy代表相关联的代理实例,第二个参数Method method代表代理实例调用的方法,这个方法也可以来自于代理接口的父接口,第三个参数Object[] args代表方法传入的参数,基类型(如int,double)会升级为对应的包装类(如Integer和Double),若未传参,则为null

invoke()方法的返回值就是代理实例调用方法后的返回值

proxy – the proxy instance that the method was invoked on

method – the Method instance corresponding to the interface method invoked on the proxy instance. The declaring class of the Method object will be the interface that the method was declared in, which may be a superinterface of the proxy interface that the proxy class inherits the method through.

args – an array of objects containing the values of the arguments passed in the method invocation on the proxy instance, or null if interface method takes no arguments. Arguments of primitive types are wrapped in instances of the appropriate primitive wrapper class, such as java.lang.Integer or java.lang.Boolean.

Java动态代理 —— 代理类的特性

更多详细的特性介绍请参考Oracle的JDK官方文档

  • 代理类保留以字符串" $ Proxy"开头的类名称的空间,所以当我们看到含"$ Proxy"的报错信息时,很有可能就是代理的错误

The space of class names that begin with the string "$Proxy" should be, however, reserved for proxy classes.

  • 我们可以在代理类上调用getInterface()方法获它的取代理接口,调用getMethods()方法获取所有代理接口的方法,调用getMethod()方法获取指定的代理接口的方法

Since a proxy class implements all of the interfaces specified at its creation, invoking getInterfaces on its Class object will return an array containing the same list of interfaces (in the order specified at its creation), invoking getMethods on its Class object will return an array of Method objects that include all of the methods in those interfaces, and invoking getMethod will find methods in the proxy interfaces as would be expected.

  • 我们可以通过Proxy.isProxyClass()方法判断一个类是否是代理类

The Proxy.isProxyClass method will return true if it is passed a proxy class-- a class returned by Proxy.getProxyClass or the class of an object returned by Proxy.newProxyInstance-- and false otherwise.

  • 每一个代理类都有一个公共的构造函数接受一个InvocationHandler实例,这也是代理实例和InvocationHandler建立关联的过程

Each proxy class has one public constructor that takes one argument, an implementation of the interface InvocationHandler, to set the invocation handler for a proxy instance.

Java动态代理 —— 代理实例的特性

  • 我们可以通过Proxy.getInvocationHandler()静态方法获得与代理对象相关联的InvocationHandler

The static Proxy.getInvocationHandler method will return the invocation handler associated with the proxy instance passed as its argument.

  • 如前所述,代理对象的方法调用会被转发到invoke方法,包括java.lang.Object类中的hashCode()、equals()和toString()方法( 注意Object的其它方法不会经过invoke() )

An invocation of the hashCode, equals, or toString methods declared in java.lang.Object on a proxy instance will be encoded and dispatched to the invocation handler's invoke method in the same manner as interface method invocations are encoded and dispatched, as described above.

The declaring class of the Method object passed to invoke will be java.lang.Object. Other public methods of a proxy instance inherited from java.lang.Object are not overridden by a proxy class, so invocations of those methods behave like they do for instances of java.lang.Object.

Java动态代理 —— 方法调用的注意点

我们可能会碰到,在不同的接口中存在同名方法的情况,此时invoke()方法调用哪个代理接口的方法会按照传递给代理类的代理接口的顺序,即getProxyClass()方法内的接口的顺序,而不是实现类继承接口的顺序

when a duplicate method is invoked on a proxy instance, the Method object for the method in the foremost interface that contains the method (either directly or inherited through a superinterface) in the proxy class's list of interfaces is passed to the invocation handler's invoke method, regardless of the reference type through which the method invocation occurred.

例如我们现在有两个接口,他们都有相同的方法

public interface FirstInterface {

  String sayHello();
}

public interface SecondInterface {

  String sayHello();
}

实现类的implements顺序为SecondInterface,FirstInterface

public class TwoInterfaceImpl implements SecondInterface, FirstInterface {

  @Override

  public String sayHello() {

    return "hello world!";
  }
}

下面是测试方法

@Test
public void helloProxy2() throws Exception {

  Class<?> proxyClass = Proxy.getProxyClass(

    SecondInterface.class.getClassLoader(),

    FirstInterface.class, SecondInterface.class);

  InvocationHandler handler = new InvocationHandler() {

    @Override

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

      System.out.println(method.getDeclaringClass().getName());

      return method.invoke(new TwoInterfaceImpl(), args);
    }
  };

  SecondInterface foo = (SecondInterface) proxyClass.getConstructor(InvocationHandler.class)
                                                  .newInstance(handler);

  System.out.println(foo.sayHello());
}

输出结果为

特别的,对于hashCode(),equals()和toString()方法,他们的"代理接口"为java.lang.Object

If a proxy interface contains a method with the same name and parameter signature as the hashCode, equals, or toString methods of java.lang.Object, when such a method is invoked on a proxy instance, the Method object passed to the invocation handler will have java.lang.Object as its declaring class.

CGLib代理 —— Enhancer增强处理

Java的动态代理要求实实现类有对应的接口,而CGLib代理不要求一定有接口

如有一个服务实现类PersonService

public class PersonService{

  public String sayHello(String name) {

    return "hello " + name;
  }

  public int lengthOfName(String name) {

    return name.length();
  }
}

我们可以通过Enhancer拦截方法调用

@Test
public void helloProxy2() {

  Enhancer enhancer = new Enhancer();

  enhancer.setSuperclass(PersonService.class);
  enhancer.setCallback(new MethodInterceptor() {

    @Override

    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {

      if (method.getDeclaringClass() != Object.class && method.getReturnType() == String.class) {

        return "hello Tom!";
      } else {

        return proxy.invokeSuper(obj, args);
      }
    }
  });

  PersonService proxy = (PersonService) enhancer.create();

  assertEquals("hello Tom!", proxy.sayHello(null));

  assertEquals(4, proxy.lengthOfName("Mary"));
}

如果被调用方法的声明类不是Object并且返回类型是String,则返回"hello Tom!",否则正常调用lengthOfName()方法

CGLib代理 —— FastClass

CGLib既然能够应对没有接口的情况,自然也能应对存在接口时的情况,我们为上面的PersonService抽取一个接口

public interface PersonInterface {

  String sayHello(String name);

  int lengthOfName(String name);
}

下面的写法,我们已经在上一篇RPC框架的文章中已经有了初步认识

@Test
public void FastTest() throws InvocationTargetException {

  FastClass fastClass = FastClass.create(PersonInterface.class);

  FastMethod fastMethod = fastClass.getMethod("sayHello", new Class<?>[]{String.class});

  String res = (String) fastMethod.invoke(new PersonService(), new Object[]{"Tom"});

  assertEquals("hello Tom", res);
}

CGLib代理 —— Bean Creator

我们可以根据自己的需要生成一个临时的Bean实例,向Bena中添加的字段会自动生成setter()和getter()方法

@Test
public void BeanCreateTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

  BeanGenerator generator = new BeanGenerator();

  generator.addProperty("name", String.class);

  Object myBean = generator.create();

  Method setter = myBean.getClass().getMethod("setName", String.class);

  setter.invoke(myBean, "Mary");

  Method getter = myBean.getClass().getMethod("getName");

  assertEquals("Mary", getter.invoke(myBean));
}

CGLib —— Mixin

我们可以根据需要,将多个接口的功能混合到一个的接口中,但是要求每个接口都有它的实现类

第一个接口

public interface FirstInterface {

  String getFirst();
}

第一个接口的实现类如下

public class FirstImpl implements FirstInterface {

  @Override

  public String getFirst() {

    return "first behavior";
  }
}

然后是第二个接口

public interface SecondInterface {

  String getSecond();
}

第二个接口的实现类如下

public class SecondImpl implements SecondInterface {

  @Override

  public String getSecond() {

    return "second behavior";
  }
}

创建一个新的接口将上面两个接口进行组合

public interface MixInterface extends FirstInterface, SecondInterface {
}

最后设置代理,我们可以看到MixInterface的代理实例同时具备了两个接口的实现类的功能

@Test
public void MixinTest() {

  Mixin mixin = Mixin.create(

    new Class<?>[]{FirstInterface.class, SecondInterface.class, MixInterface.class},

    new Object[]{new FirstImpl(), new SecondImpl()}
  );

  MixInterface mixInterface = (MixInterface) mixin;

  assertEquals("first behavior", mixInterface.getFirst());

  assertEquals("second behavior", mixInterface.getSecond());
}

Java动态代理和CGLib代理的更多相关文章

  1. Spring中AOP的两种代理方式(Java动态代理和CGLIB代理)

    第一种代理即Java的动态代理方式上一篇已经分析,在这里不再介绍,现在我们先来了解下GCLIB代理是什么?它又是怎样实现的?和Java动态代理有什么区别? cglib(Code Generation ...

  2. Spring中AOP的两种代理方式(Java动态代理和CGLIB代理-转载

    内容是摘抄的,不知最初的原作者,见谅 Java 动态代理.具体有如下四步骤: 通过实现 InvocationHandler 接口创建自己的调用处理器: 通过为 Proxy 类指定 ClassLoade ...

  3. java面试-java动态代理和cglib代理

      代理模式就是为了提供额外或不同的操作,而插入的用来替代实际对象的对象,这些操作涉及到与实际对象的通信,因此代理通常充当中间人角色 一.java动态代理   java动态代理可以动态地创建代理并动态 ...

  4. SpringAOP-JDK 动态代理和 CGLIB 代理

    在 Spring 中 AOP 代理使用 JDK 动态代理和 CGLIB 代理来实现,默认如果目标对象是接口,则使用 JDK 动态代理,否则使用 CGLIB 来生成代理类. 1.JDK 动态代理 那么接 ...

  5. 静态代理、动态代理和cglib代理

    转:https://www.cnblogs.com/cenyu/p/6289209.html 代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象.这样做的好处 ...

  6. 设计模式---JDK动态代理和CGLIB代理

    Cglig代理设计模式 /*测试类*/ package cglibProxy; import org.junit.Test; public class TestCglib { @Test public ...

  7. JDK动态代理和 CGLIB 代理

    JDK动态代理和 CGLIB 代理 JDK动态代理:其代理对象必须是某个接口的实现,它是通过在运行期期间创建一个接口的实现类来完成对目标对象的代理. 代码示例 接口 public interface ...

  8. Java三种代理模式:静态代理、动态代理和cglib代理

    一.代理模式介绍 代理模式是一种设计模式,提供了对目标对象额外的访问方式,即通过代理对象访问目标对象,这样可以在不修改原目标对象的前提下,提供额外的功能操作,扩展目标对象的功能. 简言之,代理模式就是 ...

  9. JDK动态代理和CGLIB代理的区别

    一.原理区别: java动态代理是利用反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理. 而cglib动态代理是利用asm开源包,对代理对象类的class文件 ...

随机推荐

  1. C# CLR简介

     (一)CLR介绍 CLR是一个可以由多编程语言使用的运行时,CLR的核心功能:内存管理,程序集加载,安全性,异常处理,线程同步等等.可以被很多属于微软系列的开发语言使用. 事实上,在运行时,CLR根 ...

  2. Android studio常用快捷键导包的设置

    下面是一些快捷键的使用还有快速导包的设置 1. Ctrl+G 同时按下Ctrl+G快捷键弹出快速定位框,在框中输入行数点击OK即可快速切换到对应的行数,如图2.17所示. 2. Ctrl+E 同时按下 ...

  3. Activity通过bundle传递数据

    从AActivity.java向BActivity.java传递数据: 建立AActivity.java文件建立bundle: 1 public class AActivity extends App ...

  4. maven实现compile时将资源目录输出到target中

    由于现在项目采用的是 jboot 框架,升级最新版本2.1.5后,需要将原来的webroot资源改到 src/main/webapp目录下, 发现转移后,通过框架的app.java入口main函数无法 ...

  5. 哈工大 信息安全 实验 Snort与单台防火墙联动实验

    XX大学XX学院 <网络攻击与防御> 实验报告 实验报告撰写要求 实验操作是教学过程中理论联系实际的重要环节,而实验报告的撰写又是知识系统化的吸收和升华过程,因此,实验报告应该体现完整性. ...

  6. pep9伪代码

    Set sum to 0 Read num 1 Set sum to sum + num1 Read num2 Set sum to sum + num2 Read num3 Set sum to s ...

  7. tp5 全选,全不选 ,ajax批量删除

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. mysql常用索引

    1.索引 在关系数据库中,索引是一种单独的.物理的对数据库表中一列或多列的值进行排序的一种存储结构,它是某个表中一列或若干列值的集合和相应的指向表中物理标识这些值的数据页的逻辑指针清单.索引的作用相当 ...

  9. 拉格朗日插值法--python

    数据插补 常见插补方法 插值法--拉格朗日插值法 根据数学知识可知,对于平面上已知的n个点(无两点在一条直线上可以找到n-1次多项式 ,使次多项式曲线过这n个点. 1)求已知过n个点的n-1次多项式: ...

  10. LGP4587题解

    遇到一道题,我们该做什么? 打暴力. 此题的暴力是什么?从小到大枚举答案.但这太慢了,需要一个结论来加速一下: 若 \([1,x]\) 都能够被表示出来,新加入一个数 \(y\),若 \(y>x ...