【mybatis】源码解析 ------ reflection

一 简介

mybatis 作为ORM,实现了对象与关系数据库间的映射。mybatis中的映射包含两个方面:
1 将对象中的值(parameterType所指定的对象)映射到具体的sql中,例如:


insert into Author (id,username,password,email,bio)
values (#{id},#{username},#{password},#{email},#{bio})

2 将查询出来的结果填充到具体的对象属性中(由resultMap/resultType指定),例如:


3 mybatis传值都是POJO,传入的时候(对象到sql)调用对象的get/is方法,传出的时候(sql到对象)调用对象的set方法,这2种都是基于Java的反射。MyBatis 在进行参数处理、结果映射等操作时 , 会涉及大量的反射操作。 Java 中的反射虽 然功能强大,但是代码编写起来比较复杂且容易出错,为了简化反射操作的相关代码, MyBatis 提供了专门的反射模块,该模块位于 org.apache.ibatis.reflection包中。


屏幕快照 2018-09-14 下午5.03.43.png

二 源码解析

2.1 Reflector&ReflectorFactory

Reflector是 MyBatis 中反射模块的基础,每个 Reflector对象都对应一个类,在 Reflector 中 缓存了反射操作需要使用的类的元信息
reflector 属性:

  private final Class type;  # 对应class类型
  private final String[] readablePropertyNames; # 可读属性名称集合
  private final String[] writeablePropertyNames; # 可写属性名称集合
  private final Map setMethods = new HashMap();# 记录了属性相应的setter方法,key 是属性名,value 是Invoke 对象
  private final Map getMethods = new HashMap(); # 属性相应 的 getter 方法集合 , key 是属 性名称, value 也是 Invoker 对象
  private final Map> setTypes = new HashMap>();# 记录了属性相应的 setter 方法 的参数值类型, key 是属性名称, value 是 setter 方法的参数类型
  private final Map> getTypes = new HashMap>();# 记录 了属性相应的 getter 方法的返回位类型, key是属性名称, value 是 getter 方法的返回位类型
  private Constructor defaultConstructor; # 默认构造方法
  private Map caseInsensitivePropertyMap = new HashMap(); # 所有属性名称的集合

reflector构造函数:

    type = clazz;
    addDefaultConstructor(clazz);
    addGetMethods(clazz);
    addSetMethods(clazz);
    addFields(clazz);
    readablePropertyNames = getMethods.keySet().toArray(new String[getMethods.keySet().size()]);
    writeablePropertyNames = setMethods.keySet().toArray(new String[setMethods.keySet().size()]);
    for (String propName : readablePropertyNames) {
      caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
    }
    for (String propName : writeablePropertyNames) {
      caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
    }

addDefaultConstructor(class) : 添加默认构造函数,对应属性defaultConstructor

  private void addGetMethods(Class cls) {
    Map> conflictingGetters = new HashMap>();
    Method[] methods = getClassMethods(cls); # 返回这个类及其父类的所以methods
    for (Method method : methods) {
      if (method.getParameterTypes().length > 0) { # 过滤为无参的method
        continue;
      }
      String name = method.getName();
      if ((name.startsWith("get") && name.length() > 3)
          || (name.startsWith("is") && name.length() > 2)) {
        name = PropertyNamer.methodToProperty(name); #方法的属性名
        addMethodConflict(conflictingGetters, name, method); # 添加冲突的method
      }
    }
    resolveGetterConflicts(conflictingGetters);
  }

如果子类覆盖父类的gettter方法,并且返回值发生变化,就会生成2个签名。例如
有类 A 及其子类 SubA, A 类中定 义了 getNames()方法,其返回值类型是 List ,而在其子类 SubA 中, 覆写了其 getNames()方法且将返回值修改成 ArrayList 类型,这种覆写在 Java语言中是合法的。最终得到 的两个方法签名分别是 java.util.List#getNames 和 java.util.ArrayList#getNames,在 Reflector.addUniqueMethods()方法中会被认为是两个不同的 方法并添加到 uniqueMethods 集合中。
Reflector.resolveGetterConflicts()方法对这种覆写 的情况进行处理,同时会将处理得到的 getter方法记录到 getMethods集合,并将其返回值类型填充到 getTypes集合 。 Reflector.resolveGetterConflicts()方法的具体实现如下:


  private void resolveGetterConflicts(Map> conflictingGetters) {
    for (Entry> entry : conflictingGetters.entrySet()) {
      Method winner = null;
      String propName = entry.getKey();
      for (Method candidate : entry.getValue()) {
        if (winner == null) {
          winner = candidate;
          continue;
        }
        Class winnerType = winner.getReturnType();
        Class candidateType = candidate.getReturnType();
        if (candidateType.equals(winnerType)) {
          if (!boolean.class.equals(candidateType)) {
            throw new ReflectionException(
                "Illegal overloaded getter method with ambiguous type for property "
                    + propName + " in class " + winner.getDeclaringClass()
                    + ". This breaks the JavaBeans specification and can cause unpredictable results.");
          } else if (candidate.getName().startsWith("is")) {
            winner = candidate;
          }
        } else if (candidateType.isAssignableFrom(winnerType)) {
          // OK getter type is descendant
        } else if (winnerType.isAssignableFrom(candidateType)) {
          winner = candidate;
        } else {
          throw new ReflectionException(
              "Illegal overloaded getter method with ambiguous type for property "
                  + propName + " in class " + winner.getDeclaringClass()
                  + ". This breaks the JavaBeans specification and can cause unpredictable results.");
        }
      }
      addGetMethod(propName, winner);
    }
  }

填充reflector属性 getMethods, getTypes

  private void addGetMethod(String name, Method method) {
    if (isValidPropertyName(name)) {
      getMethods.put(name, new MethodInvoker(method));
      Type returnType = TypeParameterResolver.resolveReturnType(method, type);
      getTypes.put(name, typeToClass(returnType));
    }
  }

Reflector.addFields()方法会处理类中定义的所有字段 , 并且将处理后的字段信息添加到 setMethods 集合、 setTypes 集合、 getMethods 集合以及 getTypes 集合中,这一点与上述的 Reflector.addGetMethods()方法是一致 的 。 Reflector.addFields()方法 的具体实现如下:

 private void addFields(Class clazz) {
    Field[] fields = clazz.getDeclaredFields();; //获取 clazz 中定义的全部字段
    for (Field field : fields) {
      if (canAccessPrivateMethods()) {
        try {
          field.setAccessible(true);
        } catch (Exception e) {
          // Ignored. This is only a final precaution, nothing we can do.
        }
      }
      if (field.isAccessible()) {
        if (!setMethods.containsKey(field.getName())) {//当 setMethods 集合不包含同名属性时,将其记录到 setMethods 集合和 setTypes 集合
          // issue #379 - removed the check for final because JDK 1.5 allows
          // modification of final fields through reflection (JSR-133). (JGB)
          // pr #16 - final static can only be set by the classloader
          int modifiers = field.getModifiers();
          if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) {//当 getMethods 集合 中不包含同名 属,l生时 ,将其记录到 getMethods 集合和 getTypes 集合
            addSetField(field);
          }
        }
        if (!getMethods.containsKey(field.getName())) {
          addGetField(field);
        }
      }
    }
    if (clazz.getSuperclass() != null) {
      addFields(clazz.getSuperclass());
    }
  }

到此 reflector初始化完毕

你可能感兴趣的:(【mybatis】源码解析 ------ reflection)