JDK动态代理源码解析
代理模式是个结构性模式,主要是在原基础上添加了一个代理类来控制访问目标类的方式,这样做的好处是双方可以不用直接通信,实现了松耦合的效果使真实对象可以更专心做自己的事(单一职责,最少知识职责)更独立,维护成本更低!!
JDK动态代理是基于接口实现的,有想过为什么要用实现,不用继承吗??
测试案例
被代理对象实现
public interface Student {
void running();
}
public class OneStudent implements Student {
@Override
public void running() {
System.out.println("走路");
}
}
代理拦截方法
public class StudentProxy implements InvocationHandler {
public OneStudent student;
public StudentProxy(OneStudent student) {
this.student = student;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("动态代理实现了");
return method.invoke(student, args); // 实现被代理类的方法
}
}
public class Demo {
public static void main(String[] args) {
Student student = (Student)Proxy.newProxyInstance(OneStudent.class.getClassLoader(), OneStudent.class.getInterfaces(), new StudentProxy(new OneStudent()));
student.running();
}
}
可以看到实现被代理对象方法时被StudentProxy的Invoke给拦截了
怎么实现的呢?
Proxy.newProxyInstance源码
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h) {
// 不重要的省略
Class<?> cl = getProxyClass0(loader, intfs);
final Constructor<?> cons = cl.getConstructor(constructorParams);
// 这里创建被代理类的实例并且传入代理对象
return cons.newInstance(new Object[]{h});
}
进去getProxyClass0看看
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
// 如果设置的代理类缓存有拿到就返回缓存副本,如果没有就ProxyClassFactory去创建
return proxyClassCache.get(loader, interfaces);
}
get方法解析
public V get(K key, P parameter) {
// 不重要的省略。。。
// 解析真实类,将被代理类转换成字节码,通过输出流方式进行修改
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
// 代理类缓存的处理
while (true) {
if (supplier != null) {
// supplier might be a Factory or a CacheValue<V> instance
V value = supplier.get();
if (value != null) {
return value;
}
}
// else no supplier in cache
// or a supplier that returned null (could be a cleared CacheValue
// or a Factory that wasn't successful in installing the CacheValue)
// lazily construct a Factory
if (factory == null) {
factory = new Factory(key, parameter, subKey, valuesMap);
}
if (supplier == null) {
supplier = valuesMap.putIfAbsent(subKey, factory);
if (supplier == null) {
// successfully installed Factory
supplier = factory;
}
// else retry with winning supplier
} else {
if (valuesMap.replace(subKey, supplier, factory)) {
// successfully replaced
// cleared CacheEntry / unsuccessful Factory
// with our Factory
supplier = factory;
} else {
// retry with current supplier
supplier = valuesMap.get(subKey);
}
}
}
}
subKeyFactory.apply(key, parameter)
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
// 检查传过来的类加载器是否拥有当前被代理类接口下的所有实现类
for (Class<?> intf : interfaces) {
/*
* Verify that the class loader resolves the name of this
* interface to the same Class object.
*/
Class<?> interfaceClass = null;
try {
interfaceClass = Class.forName(intf.getName(), false, loader);
} catch (ClassNotFoundException e) {
}
if (interfaceClass != intf) {
throw new IllegalArgumentException(
intf + " is not visible from class loader");
}
/*
* Verify that the Class object actually represents an
* interface.
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* Verify that this interface is not a duplicate.
*/
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
// 代理类的名称xxx$ProxyXX,是唯一不重复的,重复的话num++;
String proxyName = proxyPkg + proxyClassNamePrefix + num;
// 修改被代理类的字节码!!返回byte流
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
// 调用native底层方法将byte流转换成类返回
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
/*
* A ClassFormatError here means that (barring bugs in the
* proxy class generation code) there was some other
* invalid aspect of the arguments supplied to the proxy
* class creation (such as virtual machine limitations
* exceeded).
*/
throw new IllegalArgumentException(e.toString());
}
}
到这里基本主流程就走完了,看下被修改后的被代理类对象
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import 代理模式.Student;
// 可以看到为什么JDK动态代理必须实现接口了,因为它有个很重要的属性必须由子类去定义那就是InvocationHandler(接口是完全抽象的它的属性都是常量,不能被子类修改)
public final class $Proxy0 extends Proxy implements Student {
// 父类的关键属性
protected InvocationHandler h;
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m3 = Class.forName("代理模式.Student").getMethod("running");
m2 = Class.forName("java.lang.Object").getMethod("toString");
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
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);
}
}
// 被代理对象的方法全部委托的致代理对象的invoker方法
public final void running() throws {
try {
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
}
总结
通过Proxy的newProxyInstance方法生成代理类,会先查询代理类缓存,如果没有就通过ProxyFactory工厂创建代理对象。创建的代理类的过程是将被代理类的字节码进行修改,让它继承自Proxy类定义Proxy类的InvocationHandler的属性,最后将每个被代理对象的方法委托致InvocationHandler的invoke当中,这样就可以支配这个被代理类的访问方式了。