美文网首页工作生活
注释mybatis-Reflector

注释mybatis-Reflector

作者: lazyguy | 来源:发表于2019-07-05 15:18 被阅读0次
    /**
     * Copyright 2009-2019 the original author or authors.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
     * in compliance with the License. You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software distributed under the License
     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
     * or implied. See the License for the specific language governing permissions and limitations under
     * the License.
     */
    package org.apache.ibatis.reflection;
    
    import java.lang.reflect.Array;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.GenericArrayType;
    import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.ReflectPermission;
    import java.lang.reflect.Type;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Locale;
    import java.util.Map;
    import java.util.Map.Entry;
    import org.apache.ibatis.reflection.invoker.GetFieldInvoker;
    import org.apache.ibatis.reflection.invoker.Invoker;
    import org.apache.ibatis.reflection.invoker.MethodInvoker;
    import org.apache.ibatis.reflection.invoker.SetFieldInvoker;
    import org.apache.ibatis.reflection.property.PropertyNamer;
    
    /**
     * This class represents a cached set of class definition information that allows for easy mapping
     * between property names and getter/setter methods. 这个类抽取一个Class的各种相关元信息缓存起来。
     * 主要是一个JAVABEAN的property名字和对应的getter/setter方法。
     *
     * @author Clinton Begin
     */
    public class Reflector {
    
      //传入的的Class对象,实际应用的时候就是我们定义的javabean
      private final Class<?> type;
      //可读property的名字数组,只有有对应的getter方法的property才是可读的
      private final String[] readablePropertyNames;
      //同理
      private final String[] writablePropertyNames;
      //
      private final Map<String, Invoker> setMethods = new HashMap<>();
      private final Map<String, Invoker> getMethods = new HashMap<>();
      private final Map<String, Class<?>> setTypes = new HashMap<>();
      private final Map<String, Class<?>> getTypes = new HashMap<>();
      private Constructor<?> defaultConstructor;
    
      private Map<String, String> caseInsensitivePropertyMap = new HashMap<>();
    
      /**
       * 这个类的主要逻辑就是就是抽取Class的元信息,就在构造函数中完成的。
       */
      public Reflector(Class<?> clazz) {
        type = clazz;
        addDefaultConstructor(clazz);
        addGetMethods(clazz);
        addSetMethods(clazz);
        addFields(clazz);
        readablePropertyNames = getMethods.keySet().toArray(new String[getMethods.keySet().size()]);
        writablePropertyNames = setMethods.keySet().toArray(new String[setMethods.keySet().size()]);
        //将解析出来的属性再做一次大写转换作为key存起来
        for (String propName : readablePropertyNames) {
          caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
        }
        for (String propName : writablePropertyNames) {
          caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName);
        }
        //所以整个解析过程就是在解析getter/setter方法和field字段成为property。封装到对应Invoker中存起来
        //Invoker其实就是封装对应的方法/Field的简便容器
      }
    
      /**
       * Checks whether can control member accessible.
       *
       * @return If can control member accessible, it return {@literal true}
       * @since 3.5.0
       */
      public static boolean canControlMemberAccessible() {
        try {
          SecurityManager securityManager = System.getSecurityManager();
          if (null != securityManager) {
            securityManager.checkPermission(new ReflectPermission("suppressAccessChecks"));
          }
        } catch (SecurityException e) {
          return false;
        }
        return true;
      }
    
      /**
       * 抽取class的默认构造函数,就是没有任何参数那一个
       */
      private void addDefaultConstructor(Class<?> clazz) {
        /**
         * 抽取出JAVABEAN里面那个没有参数的那个构造器.注意Class类里面有很多getDeclaredXXX的方法。
         * 这个Declared的意思是声明的。所谓getDeclaredXXX,既获取由这个Class本身声明的各种对应的XXX(构造器,方法,属性,注解)
         * public,private,protected的都包括。
         * 但是不会包括从父类继承而来的,因为父类和接口的来的不是它自己“Declared”的。
         */
        Constructor<?>[] consts = clazz.getDeclaredConstructors();
        for (Constructor<?> constructor : consts) {
          if (constructor.getParameterTypes().length == 0) {
            this.defaultConstructor = constructor;
          }
        }
      }
    
      /**
       * 抽取property的Getter方法
       */
      private void addGetMethods(Class<?> cls) {
        Map<String, List<Method>> conflictingGetters = new HashMap<>();
        Method[] methods = getClassMethods(cls);
        //有参数的不符合getter方法规范,过滤掉
        for (Method method : methods) {
          if (method.getParameterTypes().length > 0) {
            continue;
          }
          String name = method.getName();
          //必须以get/is开头
          if ((name.startsWith("get") && name.length() > 3)
              || (name.startsWith("is") && name.length() > 2)) {
            //javaBean的property叫啥是由方法名决定的。所以专门写了一个工具解析对应的property
            name = PropertyNamer.methodToProperty(name);
    
            addMethodConflict(conflictingGetters, name, method);
          }
        }
        resolveGetterConflicts(conflictingGetters);
      }
    
      /**
       * 这里又一次再处理重复方法,其实任然是子类重写父类方法引起的问题。 我们在addUniqueMethods中已经过滤了一遍重载方法,为什么这里又有呢?
       * 原因是重载不仅仅是可能一模一样,也有可能返回值不同。比如父类返回List,子类返回ArrayList。 而在我们解析Signature里面返回值是算在了里面的。所以就可能出现2个方法,除了返回值不一样,其他都一样
       * 此时我们取返回值范围为较小的那个。既ArrayList
       */
      private void resolveGetterConflicts(Map<String, List<Method>> conflictingGetters) {
        for (Entry<String, List<Method>> 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);
        }
      }
    
      /**
       * 将proerty和对应的getter放入容器
       * @param name
       * @param method
       */
      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));
        }
      }
    
      private void addSetMethods(Class<?> cls) {
        Map<String, List<Method>> conflictingSetters = new HashMap<>();
        Method[] methods = getClassMethods(cls);
        for (Method method : methods) {
          String name = method.getName();
          if (name.startsWith("set") && name.length() > 3) {
            if (method.getParameterTypes().length == 1) {
              name = PropertyNamer.methodToProperty(name);
              addMethodConflict(conflictingSetters, name, method);
            }
          }
        }
        resolveSetterConflicts(conflictingSetters);
      }
    
      private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name,
          Method method) {
        List<Method> list = conflictingMethods.computeIfAbsent(name, k -> new ArrayList<>());
        list.add(method);
      }
    
      private void resolveSetterConflicts(Map<String, List<Method>> conflictingSetters) {
        for (String propName : conflictingSetters.keySet()) {
          List<Method> setters = conflictingSetters.get(propName);
          Class<?> getterType = getTypes.get(propName);
          Method match = null;
          ReflectionException exception = null;
          for (Method setter : setters) {
            Class<?> paramType = setter.getParameterTypes()[0];
            if (paramType.equals(getterType)) {
              // should be the best match
              match = setter;
              break;
            }
            if (exception == null) {
              try {
                match = pickBetterSetter(match, setter, propName);
              } catch (ReflectionException e) {
                // there could still be the 'best match'
                match = null;
                exception = e;
              }
            }
          }
          if (match == null) {
            throw exception;
          } else {
            addSetMethod(propName, match);
          }
        }
      }
    
      private Method pickBetterSetter(Method setter1, Method setter2, String property) {
        if (setter1 == null) {
          return setter2;
        }
        Class<?> paramType1 = setter1.getParameterTypes()[0];
        Class<?> paramType2 = setter2.getParameterTypes()[0];
        if (paramType1.isAssignableFrom(paramType2)) {
          return setter2;
        } else if (paramType2.isAssignableFrom(paramType1)) {
          return setter1;
        }
        throw new ReflectionException(
            "Ambiguous setters defined for property '" + property + "' in class '"
                + setter2.getDeclaringClass() + "' with types '" + paramType1.getName() + "' and '"
                + paramType2.getName() + "'.");
      }
    
      private void addSetMethod(String name, Method method) {
        if (isValidPropertyName(name)) {
          setMethods.put(name, new MethodInvoker(method));
          Type[] paramTypes = TypeParameterResolver.resolveParamTypes(method, type);
          setTypes.put(name, typeToClass(paramTypes[0]));
        }
      }
    
      private Class<?> typeToClass(Type src) {
        Class<?> result = null;
        if (src instanceof Class) {
          result = (Class<?>) src;
        } else if (src instanceof ParameterizedType) {
          result = (Class<?>) ((ParameterizedType) src).getRawType();
        } else if (src instanceof GenericArrayType) {
          Type componentType = ((GenericArrayType) src).getGenericComponentType();
          if (componentType instanceof Class) {
            result = Array.newInstance((Class<?>) componentType, 0).getClass();
          } else {
            Class<?> componentClass = typeToClass(componentType);
            result = Array.newInstance(componentClass, 0).getClass();
          }
        }
        if (result == null) {
          result = Object.class;
        }
        return result;
      }
    
      /**
       * 抽取Class本身的成员变量field,注意它不是javaBean中的property
       * @param clazz
       */
      private void addFields(Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
          //如果之前通过解析getter/setter得到的property没有包含当前field,
          //也会解析出来放入对应的setMethods,getMethods,getTypes
          //而且同理,父类的field依样画葫芦
          if (!setMethods.containsKey(field.getName())) {
            // 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))) {
              addSetField(field);
            }
          }
          if (!getMethods.containsKey(field.getName())) {
            addGetField(field);
          }
        }
        if (clazz.getSuperclass() != null) {
          addFields(clazz.getSuperclass());
        }
      }
    
      private void addSetField(Field field) {
        if (isValidPropertyName(field.getName())) {
          setMethods.put(field.getName(), new SetFieldInvoker(field));
          Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
          setTypes.put(field.getName(), typeToClass(fieldType));
        }
      }
    
      private void addGetField(Field field) {
        if (isValidPropertyName(field.getName())) {
          getMethods.put(field.getName(), new GetFieldInvoker(field));
          Type fieldType = TypeParameterResolver.resolveFieldType(field, type);
          getTypes.put(field.getName(), typeToClass(fieldType));
        }
      }
    
      private boolean isValidPropertyName(String name) {
        return !(name.startsWith("$") || "serialVersionUID".equals(name) || "class".equals(name));
      }
    
      /**
       * This method returns an array containing all methods declared in this class and any superclass.
       * We use this method, instead of the simpler <code>Class.getMethods()</code>, because we want to
       * look for private methods as well.
       *
       * 这是一个反射API很常见的使用场景,获取一个类的“所有方法”。 因为getDeclaredMethods和getMethods, 前者不能获取父类接口的方法,后者不能获取私有方法。
       * 所以就用getDeclaredMethods和循环往上查找来获取所有方法。
       *
       * @param cls The class
       * @return An array containing all methods in this class
       */
      private Method[] getClassMethods(Class<?> cls) {
        Map<String, Method> uniqueMethods = new HashMap<>();
        Class<?> currentClass = cls;
        while (currentClass != null && currentClass != Object.class) {
          addUniqueMethods(uniqueMethods, currentClass.getDeclaredMethods());
    
          // we also need to look for interface methods -
          // because the class may be abstract
          Class<?>[] interfaces = currentClass.getInterfaces();
          for (Class<?> anInterface : interfaces) {
            addUniqueMethods(uniqueMethods, anInterface.getMethods());
          }
    
          currentClass = currentClass.getSuperclass();
        }
    
        Collection<Method> methods = uniqueMethods.values();
    
        return methods.toArray(new Method[methods.size()]);
      }
    
      /**
       * 这个方法会先剔除掉桥接方法,同时剔除掉重复的方法。 为什么一个类里面会有重复方法? 当子类重写了父类的一个方法时,父类和子类的Class.getDeclaredMethods都能取到同名的一个方法,虽然声明的类不同
       * 但我们的getSignature不考虑class的名字作为key,显然我们只想要子类的,所以后面加入的就不用放入map了
       */
      private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) {
        for (Method currentMethod : methods) {
          if (!currentMethod.isBridge()) {
            //key的拼接规则
            //Reflector.getSignature(Method)方法的唯一签名是:
            //java.lang.String#getSignature:java.lang.reflect.Method
            String signature = getSignature(currentMethod);
            // check to see if the method is already known
            // if it is known, then an extended class must have
            // overridden a method
            if (!uniqueMethods.containsKey(signature)) {
              uniqueMethods.put(signature, currentMethod);
            }
          }
        }
      }
    
      private String getSignature(Method method) {
        StringBuilder sb = new StringBuilder();
        Class<?> returnType = method.getReturnType();
        if (returnType != null) {
          sb.append(returnType.getName()).append('#');
        }
        sb.append(method.getName());
        Class<?>[] parameters = method.getParameterTypes();
        for (int i = 0; i < parameters.length; i++) {
          if (i == 0) {
            sb.append(':');
          } else {
            sb.append(',');
          }
          sb.append(parameters[i].getName());
        }
        return sb.toString();
      }
    
      /**
       * Gets the name of the class the instance provides information for.
       *
       * @return The class name
       */
      public Class<?> getType() {
        return type;
      }
    
      public Constructor<?> getDefaultConstructor() {
        if (defaultConstructor != null) {
          return defaultConstructor;
        } else {
          throw new ReflectionException("There is no default constructor for " + type);
        }
      }
    
      public boolean hasDefaultConstructor() {
        return defaultConstructor != null;
      }
    
      public Invoker getSetInvoker(String propertyName) {
        Invoker method = setMethods.get(propertyName);
        if (method == null) {
          throw new ReflectionException(
              "There is no setter for property named '" + propertyName + "' in '" + type + "'");
        }
        return method;
      }
    
      public Invoker getGetInvoker(String propertyName) {
        Invoker method = getMethods.get(propertyName);
        if (method == null) {
          throw new ReflectionException(
              "There is no getter for property named '" + propertyName + "' in '" + type + "'");
        }
        return method;
      }
    
      /**
       * Gets the type for a property setter.
       *
       * @param propertyName - the name of the property
       * @return The Class of the property setter
       */
      public Class<?> getSetterType(String propertyName) {
        Class<?> clazz = setTypes.get(propertyName);
        if (clazz == null) {
          throw new ReflectionException(
              "There is no setter for property named '" + propertyName + "' in '" + type + "'");
        }
        return clazz;
      }
    
      /**
       * Gets the type for a property getter.
       *
       * @param propertyName - the name of the property
       * @return The Class of the property getter
       */
      public Class<?> getGetterType(String propertyName) {
        Class<?> clazz = getTypes.get(propertyName);
        if (clazz == null) {
          throw new ReflectionException(
              "There is no getter for property named '" + propertyName + "' in '" + type + "'");
        }
        return clazz;
      }
    
      /**
       * Gets an array of the readable properties for an object.
       *
       * @return The array
       */
      public String[] getGetablePropertyNames() {
        return readablePropertyNames;
      }
    
      /**
       * Gets an array of the writable properties for an object.
       *
       * @return The array
       */
      public String[] getSetablePropertyNames() {
        return writablePropertyNames;
      }
    
      /**
       * Check to see if a class has a writable property by name.
       *
       * @param propertyName - the name of the property to check
       * @return True if the object has a writable property by the name
       */
      public boolean hasSetter(String propertyName) {
        return setMethods.keySet().contains(propertyName);
      }
    
      /**
       * Check to see if a class has a readable property by name.
       *
       * @param propertyName - the name of the property to check
       * @return True if the object has a readable property by the name
       */
      public boolean hasGetter(String propertyName) {
        return getMethods.keySet().contains(propertyName);
      }
    
      public String findPropertyName(String name) {
        return caseInsensitivePropertyMap.get(name.toUpperCase(Locale.ENGLISH));
      }
    }
    

    相关文章

      网友评论

        本文标题:注释mybatis-Reflector

        本文链接:https://www.haomeiwen.com/subject/gplrhctx.html