JDK1.8动态代理源码分析

本文记录了对JDK1.8动态代理源码的研究,详细阐述了Proxy.newProxyInstance方法如何生成Mapper代理类,以及WeakCache的get方法在首次调用时如何创建代理类对象并缓存,后续调用则从缓存中获取。同时指出动态代理类只生成一次并保存,每次调用都会创建新的实例。代理类继承自Proxy,仅支持接口方式,不支持继承。最后,InvocationHandler的实现类对象在代理类构造时传入,代理方法由其invoke方法执行。
摘要由CSDN通过智能技术生成

最近在学习MyBatis源码时,想要查看下JDK是如何自动生成的Mapper代理类。于是仔细看了源码,在这里做个记录。

package com.br.itwzhangzx02.learn;

import learn.User;
import learn.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;

public class GeneratorClassFileTest {

  public static void main(String[] args) {
    //将生成的代理类class文件保存在磁盘
    System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
    String resource = "resources/mybatis-config.xml";
    SqlSessionFactory sqlSessionFactory;
    try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
      //1、创建SqlSessionFactory
      sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      //2、获取sqlSession
      SqlSession sqlSession = sqlSessionFactory.openSession();
      User user = getUser(sqlSession);
      System.out.println(user);
    }catch (Exception e){
    }
  }

  private static User getUser(SqlSession sqlSession) {
    //3、获取mapper,断点在这儿,然后进入
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    userMapper.toString();
    //4、执行数据库操作,并处理结果集
    return userMapper.selectUser("10");
  }
  
}

 //MapperProxyFactory 类中的方法 第三个入参mapperProxy就是实现了InvocationHandler接口的类的对象
protected T newInstance(MapperProxy<T> mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }



//这个是MapperRegistry类中的方法,将mapperProxyFactory 在初始化解析xml时缓存到内存中。
 public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {//这儿,用对应的工厂负责new一个代理类的对象
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }

然后直接查看我们JDK的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);
        }

        /* 第一步:
         * Look up or generate the designated proxy class.
         * 这里使用到缓存技术,从缓存中取代理类,或者直接生成一个代理类
         */
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        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);
           
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值