JDK动态代理的完整思路以及流程
JDK动态代理的流程图
从图中可以大致看到动态代理的流程,入口类就是自定义的invocationHandler,的invoke方法执行生成代理类对象,通过生成代理类之后,执行被代理类的方法,而代理类是通过getProxyFactory工厂,动态生成代理类的字节码,从而提供计算机执行的机器码。
而在代码调用层面入口代码
/* 关注公众号 孤独的投机家 有更多的视频学习资料*/
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//生成$Proxy0的class文件
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
IHello ihello = (IHello) Proxy.newProxyInstance(IHello.class.getClassLoader(), //加载接口的类加载器
new Class[]{
IHello.class}, //一组接口
new HWInvocationHandler(new Hello())); //自定义的InvocationHandler
ihello.sayHello();
}
注意这里的Proxy.newProxyInstance,这里是通过proxy获取到代理类实例过程,核心的参数分别为代理类的加载器,代理类实现的接口,代理类实现的接口方法。
Proxy.getProxyClass,JDK动态代理源码入口
核心提炼后的代码,大致如下,
/* 关注公众号 孤独的投机家 有更多的视频学习资料*/
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
if (h == null) {
//如果h为空直接抛出异常,所以InvocationHandler实例对象是必须的
throw new NullPointerException();
}
//对象的拷贝,暂不知道这里拷贝下的意义是啥?
final Class<?>[] intfs = interfaces.clone();
//一些安全的权限检查
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
//产生代理类
Class<?> cl = getProxyClass0(loader, intfs);
//获取代理类的构造函数对象
//参数constructorParames为常量值:private static final Class<?>[] constructorParams = { InvocationHandler.class };
final Constructor<?> cons = cl.getConstructor(constructorParames);
final InvocationHandler ih = h;
//根据代理类的构造函数对象来创建代理类对象
return newInstance(cons, ih);
}
这里的核心处理就是流程图里面介绍的,通过加载器以及接口获取代理类类型的实例,从而通过获取构造器,实例化返回实例对象。
ProxyClassFactory,生成代理类的核心,包括对字节码的动态生成以及执行
从JDK的源码来分析,核心的处理流程就是流程图的大图介绍,把生成的代理类,动态生成字节码,而非通过编译的方式生成,没有通过JVM的方式生成机器码
```java
/* 关注公众号 孤独的投机家 有更多的视频学习资料*/
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
//统一代理类的前缀名都以$Proxy开关
private static final String proxyClassNamePrefix = "$Proxy";
//使用唯一的编号给作为代理类名的一部分,如$Proxy0,$Proxy1等
private static final AtomicLong nextUniqueNumber = new AtomicLong();
@Override
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
for (Class<?> intf : interfaces) {
//验证指定的类加载器(loader)加载接口所得到的Class对象(interfaceClass)是否与intf对象相同
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");
}
//验证该Class对象是不是接口
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(