Java动态代理和CGLib代理
本文参考
在上一篇"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代理的更多相关文章
- Spring中AOP的两种代理方式(Java动态代理和CGLIB代理)
第一种代理即Java的动态代理方式上一篇已经分析,在这里不再介绍,现在我们先来了解下GCLIB代理是什么?它又是怎样实现的?和Java动态代理有什么区别? cglib(Code Generation ...
- Spring中AOP的两种代理方式(Java动态代理和CGLIB代理-转载
内容是摘抄的,不知最初的原作者,见谅 Java 动态代理.具体有如下四步骤: 通过实现 InvocationHandler 接口创建自己的调用处理器: 通过为 Proxy 类指定 ClassLoade ...
- java面试-java动态代理和cglib代理
代理模式就是为了提供额外或不同的操作,而插入的用来替代实际对象的对象,这些操作涉及到与实际对象的通信,因此代理通常充当中间人角色 一.java动态代理 java动态代理可以动态地创建代理并动态 ...
- SpringAOP-JDK 动态代理和 CGLIB 代理
在 Spring 中 AOP 代理使用 JDK 动态代理和 CGLIB 代理来实现,默认如果目标对象是接口,则使用 JDK 动态代理,否则使用 CGLIB 来生成代理类. 1.JDK 动态代理 那么接 ...
- 静态代理、动态代理和cglib代理
转:https://www.cnblogs.com/cenyu/p/6289209.html 代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象.这样做的好处 ...
- 设计模式---JDK动态代理和CGLIB代理
Cglig代理设计模式 /*测试类*/ package cglibProxy; import org.junit.Test; public class TestCglib { @Test public ...
- JDK动态代理和 CGLIB 代理
JDK动态代理和 CGLIB 代理 JDK动态代理:其代理对象必须是某个接口的实现,它是通过在运行期期间创建一个接口的实现类来完成对目标对象的代理. 代码示例 接口 public interface ...
- Java三种代理模式:静态代理、动态代理和cglib代理
一.代理模式介绍 代理模式是一种设计模式,提供了对目标对象额外的访问方式,即通过代理对象访问目标对象,这样可以在不修改原目标对象的前提下,提供额外的功能操作,扩展目标对象的功能. 简言之,代理模式就是 ...
- JDK动态代理和CGLIB代理的区别
一.原理区别: java动态代理是利用反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理. 而cglib动态代理是利用asm开源包,对代理对象类的class文件 ...
随机推荐
- GAN实战笔记——第五章训练与普遍挑战:为成功而GAN
训练与普遍挑战:为成功而GAN 一.评估 回顾一下第1章中伪造达・芬奇画作的类比.假设一个伪造者(生成器)正在试图模仿达・芬奇,想使这幅伪造的画被展览接收.伪造者要与艺术评论家(判别器)竞争,后者试图 ...
- Java:安装新版本Java、环境配置
最新版2021年版 Java安装目录 2.在系统变量中设置2项属性,JAVA_HOME.PATH(大小写无所谓),若已存在这点击编辑,不存在则新建 参数为: JAVA_HOME: D:\Java\ ...
- jieba:统计一篇文章中词语数
jieba官方文档 1.jieba分词的四种模式 精确模式.全模式.搜索引擎模式.paddle模式 精确模式:把文本精确的切分开,不存在冗余单词,适合文本分析: 全模式:把文本中所有可能的词语都扫描出 ...
- C# Winform中FpSpread表格控件设置固定的(冻结的)行或列
在项目中我们经常会用到固定表头的操作,FpSpread提供了冻结行或列的属性. 你可以冻结表单中的行或列(使其不可滚动). 你可以冻结任意个表单顶部的行,使其成为前导行,你也可以冻结左侧任意多个列,使 ...
- CSDN中Markdown编辑器使用方法
Markdown编辑器 如果想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识. 新的改变 CSDN中Markdown编辑器进行了一些功能拓展与语法支 ...
- LeetCode-001-两数之和
两数之和 题目描述:给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标. 你可以假设每种输入只会对应一个答 ...
- Python自动化 unittest生成测试报告(HTMLTestRunner)03
批量执行完用例后,生成的测试报告是文本形式的,不够直观,为了更好的展示测试报告,最好是生成HTML格式的. unittest里面是不能生成html格式报告的,需要导入一个第三方的模块:HTMLTest ...
- SQL从零到迅速精通【数据库应用】
数据库理论的研究主要集中于关系规范化理论和关系数据理论等.数据库技术与计算机技术的结合使得数据库中新的技术层出不穷.最初的数据库系统主要应用于银行管理.飞机订票等事务处理环境.后来渐渐应用于工程设计与 ...
- phpstrom2019版永久破解
前言 : 首先进入软件,如果软件需要激活才能进入,可以在idea.medeming.com/jets,中下载激活码,以方便进入 然后按照下面的步骤操作 1.下载补丁 链接:https://pan.ba ...
- OpenTracing 简介
自从 Google Dapper 的论文发布之后,各大互联网公司和开源社区开发的分布式链路追踪产品百花齐放,同时也给使用者带来了一个问题,各个分布式链路追踪产品的 API 并不兼容,如果用户在各个产品 ...