本篇文章针对的是对动态代理想要进行深入研究的小伙伴而写,即我们深入源码进行研究
JDK动态代理
小例子
先上一个动态代理的小例子:
public interface IRequest {
public void doGet() throws InterruptedException ;
}
public class Request implements IRequest{
@Override
public void doGet() throws InterruptedException {
System.out.println("处理请求中...");
Thread.sleep(new Random().nextInt(10));
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Request request=new Request();
IRequest proxyInstance = (IRequest)Proxy.newProxyInstance(request.getClass().getClassLoader(),
request.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long start = System.currentTimeMillis();
Object invoke = method.invoke(request, args);
long end = System.currentTimeMillis();
System.out.println("请求耗时为 :" + String.valueOf(end - start) + "毫秒");
return invoke;
}
});
proxyInstance.doGet();
}
}
JDK动态代理源码探究
首先,我们利用ProxyGenerator来手动生成上面Request的代理对象,放入到当前项目的target目录下面,这样我们就可以利用编译器自动反编译class文件的功能,而不需要自己手动去反编译了
public class Main {
public static void main(String[] args) throws InterruptedException {
byte[] proxyClass = ProxyGenerator.generateProxyClass("$Proxy0", Request.class.getInterfaces());
String path=System.getProperty("user.dir")+"/target/classes/com/RequestProxy.class";
try(FileOutputStream out=new FileOutputStream(path))
{
out.write(proxyClass);
out.flush();
System.out.println("写入完毕");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
生成的代理对象源码如下:
import com.staticProxy.IRequest;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class $Proxy0 extends Proxy implements IRequest {
private static Method m1;
private static Method m2;
private static Method m3;
private static Method m0;
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}
public final boolean equals(Object var1) throws {
try {
return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final String toString() throws {
try {
return (String)super.h.invoke(this, m2, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final void doGet() throws InterruptedException {
try {
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | InterruptedException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final int hashCode() throws {
try {
return (Integer)super.h.invoke(this, m0, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m2 = Class.forName("java.lang.Object").getMethod("toString");
m3 = Class.forName("com.staticProxy.IRequest").getMethod("doGet");
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
InvocationHandler接口
我相信看了上面jdk默认生成的代理对象源码,大家肯定对InvocationHandler和Proxy特别感兴趣,下面我们逐个击破,首先是InvocationHandler接口的分析
public interface InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
}
其实这就是个函数式接口,只有一个需要用户实现的invoke方法。
IRequest proxyInstance = (IRequest)Proxy.newProxyInstance(request.getClass().getClassLoader(),
request.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long start = System.currentTimeMillis();
Object invoke = method.invoke(request, args);
long end = System.currentTimeMillis();
System.out.println("请求耗时为 :" + String.valueOf(end - start) + "毫秒");
return invoke;
}
});
在我们通过Proxy对象的newProxyInstance方法创建代理对象的时候,我们会在该方法第三个参数传入InvocationHandler 接口的一个实现类,然后生成的代理对象继承Proxy类,并且通过Proxy类的InvocationHandler类型的成员变量保存了我们传入的InvocationHandler接口的实现类,然后在代理对象执行每个被代理对象方法时,都是通过InvocationHandler的invoke方法执行的
Proxy类
我们来分析一下神秘的newProxyInstance方法:
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h);
final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
Class<?> cl = getProxyClass0(loader, intfs);
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
Proxy其他注意点:
public class Proxy implements java.io.Serializable {
private static final long serialVersionUID = -2222568056686623797L;
private static final Class<?>[] constructorParams =
{ InvocationHandler.class };
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
protected InvocationHandler h;
private Proxy() {
}
protected Proxy(InvocationHandler h) {
Objects.requireNonNull(h);
this.h = h;
}
.....
坑
结论: 红色画出的那一行代码会造成死循环,大家思考为什么?
上面说过代理对象的方法调用最终会调用InvocationHandler的invoke方法,那如果我们在InvocationHandler的invoke方法中继续调用代理对象的方法,不就进入一个死循环了吗?
我们这里的本意是通过InvocationHandler的invoke方法对被代理对象的方法进行增强,因此这里method对象关联的实例对象应该是被代理的对象,这里大家不要搞混了。
Cglib代理
CGLIB是一个强大的高性能的代码生成包。
CGLIB是针对类实现代理,主要是对指定的类生成一个子类,覆盖其中的方法(继承);
利用ASM开源包,对代理对象类的class文件加载进来,通过修改其字节码生成子类来处理。
Cglib的原理这里不会剖析的特别深入,感兴趣的小伙伴可以自行去查看他的源码,顺便还可以学习一下ASM框架的使用
导入相关依赖
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
小例子
public class Request{
public void doGet() throws InterruptedException {
System.out.println("处理请求中...");
Thread.sleep(new Random().nextInt(10));
}
}
public class ProxyFactory implements MethodInterceptor
{
private Object target;
public ProxyFactory(Object target)
{
this.target=target;
}
public Object getProxyInstance()
{
Enhancer enhancer=new Enhancer();
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects,
MethodProxy methodProxy) throws Throwable {
long start = System.currentTimeMillis();
Object ret= method.invoke(target, objects);
long end = System.currentTimeMillis();
System.out.println("请求耗时为 :" + String.valueOf(end - start) + "毫秒");
return ret;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
ProxyFactory proxyFactory=new ProxyFactory(new Request());
Request proxyInstance = (Request) proxyFactory.getProxyInstance();
proxyInstance.doGet();
}
}
|