mybatis 反射

addDefaultConstructor

  • mybatis 的反射相关内容在org.apache.ibatis.reflection 下存放. 本片主要讲解org.apache.ibatis.reflection.Reflector类, 先看一下该类的属性
  1. public class Reflector {
  2. /**
  3. * 实体类.class
  4. */
  5. private final Class<?> type;
  6. /**
  7. * 可读 属性
  8. */
  9. private final String[] readablePropertyNames;
  10. /**
  11. * 可写 属性值
  12. */
  13. private final String[] writablePropertyNames;
  14. /**
  15. * set 方法列表
  16. */
  17. private final Map<String, Invoker> setMethods = new HashMap<>();
  18. /**
  19. * get 方法列表
  20. */
  21. private final Map<String, Invoker> getMethods = new HashMap<>();
  22. /**
  23. * set 的数据类型
  24. */
  25. private final Map<String, Class<?>> setTypes = new HashMap<>();
  26. /**
  27. * get 的数据类型
  28. */
  29. private final Map<String, Class<?>> getTypes = new HashMap<>();
  30. /**
  31. * 构造函数
  32. */
  33. private Constructor<?> defaultConstructor;
  34. /**
  35. * 缓存数据, 大写KEY
  36. */
  37. private Map<String, String> caseInsensitivePropertyMap = new HashMap<>();
  38. }
  • 构造方法, 构造方法传入一个类的字节码,在构造方法中设置相关的属性值
  1. public class Reflector {
  2. /**
  3. * @param clazz 待解析类的字节码
  4. */
  5. public Reflector(Class<?> clazz) {
  6. type = clazz;
  7. // 构造方法
  8. addDefaultConstructor(clazz);
  9. // get 方法
  10. addGetMethods(clazz);
  11. // set 方法
  12. addSetMethods(clazz);
  13. // 字段值
  14. addFields(clazz);
  15. readablePropertyNames = getMethods.keySet().toArray(new String[0]);
  16. writablePropertyNames = setMethods.keySet().toArray(new String[0]);
  17. for (String propName : readablePropertyNames) {
  18. // 循环操作设置到缓存中,
  19. caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
  20. }
  21. for (String propName : writablePropertyNames) {
  22. caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
  23. }
  24. }
  25. }
  • addDefaultConstructor 方法 , 下面截图内容为 JDK8 mybatis 中 的内容
  1. private void addDefaultConstructor(Class<?> clazz) {
  2. // 获取类里面的所有构造方法
  3. Constructor<?>[] constructors = clazz.getDeclaredConstructors();
  4. // 过滤得到空参构造 constructor -> constructor.getParameterTypes().length == 0
  5. Arrays.stream(constructors).filter(constructor -> constructor.getParameterTypes().length == 0)
  6. .findAny().ifPresent(constructor -> {
  7. System.out.println("有空参构造");
  8. this.defaultConstructor = constructor;
  9. });
  10. }
  • 创建一个测试类
  1. public class People {
  2. private String name;
  3. public People() {
  4. }
  5. public People(String name) {
  6. this.name = name;
  7. }
  8. @Override
  9. public String toString() {
  10. return "People{" +
  11. "name='" + name + '\'' +
  12. '}';
  13. }
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. }
  1. import org.junit.jupiter.api.Test;
  2. import java.lang.reflect.Constructor;
  3. class HfReflectorTest {
  4. @Test
  5. void getDefaultConstructorTest() throws Exception {
  6. Reflector reflector = new Reflector(People.class);
  7. // 获取空参构造方法
  8. Constructor<?> defaultConstructor = reflector.getDefaultConstructor();
  9. People o = (People) defaultConstructor.newInstance();
  10. o.setName("hhh");
  11. System.out.println(o);
  12. }
  13. }
  • 准备工作完成了开始进行 debug , 在org.apache.ibatis.reflection.Reflector#addDefaultConstructor这个方法上打上断点

    1575890354400

    观察constructors属性存在两个方法,这两个方法就是我在People类中的构造方法.

    根据语法内容我们应该对parameterTypes属性进行查看

    1575890475839

可以发现空参构造的parameterTypes长度是 0.因此可以确认org.apache.ibatis.reflection.Reflector#addDefaultConstructor方法获取了空参构造

  • 继续看org.apache.ibatis.reflection.Reflector#getDefaultConstructor方法, 该方法是获取构造函数的方法,如果构造函数没有就抛出异常,这也是为什么我们的实体类需要把空参构造写上去的原因。

    1. public Constructor<?> getDefaultConstructor() {
    2. if (defaultConstructor != null) {
    3. return defaultConstructor;
    4. } else {
    5. // 如果没有空参构造抛出的异常
    6. throw new ReflectionException("There is no default constructor for " + type);
    7. }
    8. }

addGetMethods

  • 该方法获取了所有getis开头的方法

    1. private void addGetMethods(Class<?> clazz) {
    2. // 反射方法
    3. Map<String, List<Method>> conflictingGetters = new HashMap<>();
    4. Method[] methods = getClassMethods(clazz);
    5. // JDK8 filter 过滤get 开头的方法
    6. Arrays.stream(methods).filter(m -> m.getParameterTypes().length == 0 && PropertyNamer.isGetter(m.getName()))
    7. .forEach(m -> addMethodConflict(conflictingGetters, PropertyNamer.methodToProperty(m.getName()), m));
    8. resolveGetterConflicts(conflictingGetters);
    9. }
  • 该方法中依旧使用了 JDK8 语法通过m.getParameterTypes().length == 0 && PropertyNamer.isGetter(m.getName())来判断是否是get或·is开头的内容

  • 调用org.apache.ibatis.reflection.property.PropertyNamer

    1. public static boolean isGetter(String name) {
    2. // 在语义上 is 开头的也是get开头的
    3. return (name.startsWith("get") && name.length() > 3) || (name.startsWith("is") && name.length() > 2);
    4. }
  • resolveGetterConflicts方法后续介绍

getClassMethods

  • org.apache.ibatis.reflection.Reflector#getClassMethods,该方法将传入对象的所有可见方法都获取到进行唯一标识处理成一个Map对象 添加方法为org.apache.ibatis.reflection.Reflector#addUniqueMethods

    1. private Method[] getClassMethods(Class<?> clazz) {
    2. // 方法唯一标识: 方法
    3. Map<String, Method> uniqueMethods = new HashMap<>();
    4. Class<?> currentClass = clazz;
    5. while (currentClass != null && currentClass != Object.class) {
    6. // getDeclaredMethods 获取 public ,private , protcted 方法
    7. addUniqueMethods(uniqueMethods, currentClass.getDeclaredMethods());
    8. // we also need to look for interface methods -
    9. // because the class may be abstract
    10. // 当前类是否继承别的类(实现接口)如果继承则需要进行操作
    11. Class<?>[] interfaces = currentClass.getInterfaces();
    12. for (Class<?> anInterface : interfaces) {
    13. // getMethods 获取本身和父类的 public 方法
    14. addUniqueMethods(uniqueMethods, anInterface.getMethods());
    15. }
    16. // 循环往上一层一层寻找最后回到 Object 类 的上级为null 结束
    17. currentClass = currentClass.getSuperclass();
    18. }
    19. Collection<Method> methods = uniqueMethods.values();
    20. return methods.toArray(new Method[0]);
    21. }
  • org.apache.ibatis.reflection.Reflector#addUniqueMethods

    1. private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) {
    2. for (Method currentMethod : methods) {
    3. // 桥接, 具体还不知道
    4. // TODO: 2019/12/9 JAVA 桥接方法
    5. if (!currentMethod.isBridge()) {
    6. // 方法的唯一标识
    7. String signature = getSignature(currentMethod);
    8. // check to see if the method is already known
    9. // if it is known, then an extended class must have
    10. // overridden a method
    11. if (!uniqueMethods.containsKey(signature)) {
    12. uniqueMethods.put(signature, currentMethod);
    13. }
    14. }
    15. }
    16. }
  • 唯一标识方法org.apache.ibatis.reflection.Reflector#getSignature

    1. /**
    2. * 方法唯一标识,返回值类型#方法名称:参数列表
    3. *
    4. * @param method
    5. * @return
    6. */
    7. private String getSignature(Method method) {
    8. StringBuilder sb = new StringBuilder();
    9. Class<?> returnType = method.getReturnType();
    10. if (returnType != null) {
    11. sb.append(returnType.getName()).append('#');
    12. }
    13. sb.append(method.getName());
    14. Class<?>[] parameters = method.getParameterTypes();
    15. for (int i = 0; i < parameters.length; i++) {
    16. sb.append(i == 0 ? ':' : ',').append(parameters[i].getName());
    17. }
    18. return sb.toString();
    19. }
  • 照旧我们进行 debug 当前方法为toString方法

    1575891988804

    从返回结果可以看到sb.toString返回的是: 返回值类型#方法名

    1575892046692

    上图返回结果为void#setName:java.lang.String 命名规则:返回值类型#方法名称:参数列表

    回过头看看uniqueMethods里面是什么

    1575892167982

    方法签名:方法

    目前完成了一部分还有一个继承问题需要 debug 看一下, 编写一个Man继承People 还需要实现接口

    1. public class Man extends People implements TestManInterface {
    2. @Override
    3. public Integer inte() {
    4. return 1;
    5. }
    6. public String hello() {
    7. return "hello";
    8. }
    9. }
    1. public interface TestManInterface {
    2. public Integer inte();
    3. }

    目标明确了就直接在

    1575892414120

    这里打断点了

    1575892511471

    在进入循环之前回率先加载本类的所有可见方法

    1. if (!uniqueMethods.containsKey(signature)) {
    2. // 如果存在该方法唯一签名则不添加
    3. uniqueMethods.put(signature, currentMethod);
    4. }

    接下来断点继续往下走

    1575892645405

    走到这一步我们来看看currentClass.getSuperclass()是不是上一级的类

    1575892687076

    通过断点可见这个currentClass现在是People类,根据之前所说的最终uniqueMethods应该存在父类的方法

    1575892763661

    可以看到父类的方法也都存在了

resolveGetterConflicts

  • org.apache.ibatis.reflection.Reflector#resolveGetterConflicts

    这个方法解决了get方法的冲突问题,同名方法不同返回值

    1. private void resolveGetterConflicts(Map<String, List<Method>> conflictingGetters) {
    2. for (Entry<String, List<Method>> entry : conflictingGetters.entrySet()) {
    3. Method winner = null;
    4. String propName = entry.getKey();
    5. boolean isAmbiguous = false;
    6. for (Method candidate : entry.getValue()) {
    7. if (winner == null) {
    8. winner = candidate;
    9. continue;
    10. }
    11. Class<?> winnerType = winner.getReturnType();
    12. Class<?> candidateType = candidate.getReturnType();
    13. if (candidateType.equals(winnerType)) {
    14. if (!boolean.class.equals(candidateType)) {
    15. isAmbiguous = true;
    16. break;
    17. } else if (candidate.getName().startsWith("is")) {
    18. winner = candidate;
    19. }
    20. } else if (candidateType.isAssignableFrom(winnerType)) {
    21. // OK getter type is descendant
    22. } else if (winnerType.isAssignableFrom(candidateType)) {
    23. winner = candidate;
    24. } else {
    25. isAmbiguous = true;
    26. break;
    27. }
    28. }
    29. addGetMethod(propName, winner, isAmbiguous);
    30. }
    31. }

addFields

  • org.apache.ibatis.reflection.Reflector#addFields

    获取类的所有字段没什么好说的直接递归就可以获取了.

    1. private void addFields(Class<?> clazz) {
    2. Field[] fields = clazz.getDeclaredFields();
    3. for (Field field : fields) {
    4. if (!setMethods.containsKey(field.getName())) {
    5. // issue #379 - removed the check for final because JDK 1.5 allows
    6. // modification of final fields through reflection (JSR-133). (JGB)
    7. // pr #16 - final static can only be set by the classloader
    8. int modifiers = field.getModifiers();
    9. if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) {
    10. addSetField(field);
    11. }
    12. }
    13. if (!getMethods.containsKey(field.getName())) {
    14. addGetField(field);
    15. }
    16. }
    17. if (clazz.getSuperclass() != null) {
    18. addFields(clazz.getSuperclass());
    19. }
    20. }

属性查看

  • 下图为一个类的解析结果

1575894218362