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());
}