本文参考

在上一篇"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. 【windows 访问控制】一、访问令牌

    访问令牌(Access tokens) 访问令牌是描述进程或线程的安全上下文的对象.令牌中的信息包括与进程或线程关联的用户帐户的标识和特权信息.当用户登录时,系统通过将用户密码与安全数据库(如域认证中 ...

  2. 【C#操作符】typeof 和 is 运算符执行的类型检查之间的差异

    typeof 运算符也能用于公开的泛型类型.具有不止一个类型参数的类型的规范中必须有适当数量的逗号.不能重载 typeof 运算符. is 可以检测和父类是否兼容,typeof责不能 public c ...

  3. 探究Spring原理

    探究Spring原理 探究IoC原理 首先我们大致了解一下ApplicationContext的加载流程: 我们可以看到,整个过程极为复杂,一句话肯定是无法解释的,所以我们就从ApplicationC ...

  4. 哈工大 计算机系统 实验二 Datalab数据表示

    所有实验文件可见github 计算机系统实验整理 由于word文件没有保存,因此如需参考此实验,请直接访问github文件

  5. JZ-020-包含 min 函数的栈

    包含 min 函数的栈 题目描述 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1)). 题目链接: 包含 min 函数的栈 代码 import jav ...

  6. Linux swap分区操作

    swap交换分区是系统RAM的补充,swap 分区支持虚拟内存.当没有足够的 RAM 保存系统处理的数据时,会将数据写入 swap 分区,当系统缺乏 swap 空间时,内核会因 RAM 内存耗尽而终止 ...

  7. think php 图像加水印

    1.将下载好的字体引入至 thinkPHP 框架的public/static 下(这里我建了一个文件夹叫font) (1.) (2.)   2.将字体路径写入config.php中 'font'=&g ...

  8. laravel8安装步骤

    网址: https://learnku.com/docs/laravel/8.x/installation/9354 安装: # 安装laravel composer create-project - ...

  9. JavaWeb 07_创建web项目连接MySQL实现注册登录功能

    一.创建一个web项目,参照JW/01_创建web项目及部署 二.在NAVICat 里建数据库 db_01,建表tb_user ,字段UName .Pwd 三.在web下创建一个Directory, ...

  10. k8s.gcr.io、gcr.io仓库的镜像下载

    镜像下载.域名解析.时间同步请点击 阿里巴巴开源镜像站 获取这类镜像的方法一般有2种: 1.通过拉取国内镜像仓库的内容(操作简单直接拉取即可,缺点是镜像的版本更新可能较慢,可能无法获取最新的镜像) 2 ...