MyBatis 技术内幕 - 基础支持层 - 反射器模块 - Reflector

MyBatis 技术内幕 - 基础支持层 - 反射器模块 - Reflector


源码总结

  • 源码版本:MyBatis 3.4.0
  • 模块功能:
    • MyBatis 在处理参数、结果映射时使用反射机制
    • 为避免使用Java提供的反射机制出现错误,进而对其进行封装
  • 注意事项:使用MyBatis的反射类操作的类需要注意如下事项
    • 类中要有无参构造方法
      • 备注:
        • 如果类中无构造方法,系统默认添加一个无参构造方法
        • 如果手动添加了有参构造方法,需要显示添加无参构造方法
      • 原因: defaultConstructor 添加的默认构造方法为无参构造方法
    • 被反射器其类中出现属性字母相同但大小写顺序位置不同会当做同一个属性处理
      • 举例:userName 与 username
      • 原因:caseInsensitivePropertyMap 中的 KEY 值是属性的字母全大写,会发生覆盖
    • 类中过滤 final 与 staitc 修饰的属性
    • 类中允许继承,在遍历类中方法及属性时会逐级查找类的父类中的属性方法
  • 设计模式
    • 适配器模式1
      • 简介:将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)
      • 应用:MethodInvoker

源码解读


类中属性


  /**
   * 空数组
   */
  private static final String[] EMPTY_STRING_ARRAY = new String[0];

  /**
   * 类:需要反射处理的类
   */
  private Class<?> type;
  /**
   * 被反射的类中可读属性集合,初始值为空,getXXX(),isXXX()
   */
  private String[] readablePropertyNames = EMPTY_STRING_ARRAY;
  /**
   * 被反射的类中可写属性集合,初始值为空,setXXX()
   */
  private String[] writeablePropertyNames = EMPTY_STRING_ARRAY;
  /**
   * 被反射的类中属性及其可写方法映射集合
   * Key : 属性名称
   * Value : MethodInvoker 实现 Invoker 接口,MethodInvoker 是 Method 对象的封装 , 适配器模式
   */
  private Map<String, Invoker> setMethods = new HashMap<String, Invoker>();
  /**
   * 被反射的类中属性及其可读方法映射集合
   * Key : 属性名称
   * Value : MethodInvoker 实现 Invoker 接口,MethodInvoker 是 Method 对象的封装 , 适配器模式
   */
  private Map<String, Invoker> getMethods = new HashMap<String, Invoker>();
  /**
   * 被反射的类中属性及其可写方法参数类型
   * Key : 属性名称
   * Value : 参数类型
   */
  private Map<String, Class<?>> setTypes = new HashMap<String, Class<?>>();
  /**
   * 被反射的类中属性及其可读方法返回类型
   * Key : 属性名称
   * Value : 返回值类型
   */
  private Map<String, Class<?>> getTypes = new HashMap<String, Class<?>>();
  /**
   * 被反射的类的默认构造方法,无参构造方法
   */
  private Constructor<?> defaultConstructor;
  /**
   * 被反射的类中属性及其名称映射
   * Key : 属性名称大写
   * Value : 属性名称
   */
  private Map<String, String> caseInsensitivePropertyMap = new HashMap<String, String>();

构造方法


  /**
   * 构造方法
   * @param clazz
   */
  public Reflector(Class<?> clazz) {
    // 初始化:反射操作的类
    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():添加默认构造方法

  /**
   * 添加默认的构造方法(被反射类中的无参构造方法)
   * @param clazz
   */
  private void addDefaultConstructor(Class<?> clazz) {
    Constructor<?>[] consts = clazz.getDeclaredConstructors();
    // 类中所有构造方法
    for (Constructor<?> constructor : consts) {
      // 构造方法中无参数的构造方法
      if (constructor.getParameterTypes().length == 0) {
        if (canAccessPrivateMethods()) {
          try {
            constructor.setAccessible(true);
          } catch (Exception e) {
            // Ignored. This is only a final precaution, nothing we can do.
          }
        }
        if (constructor.isAccessible()) {
          this.defaultConstructor = constructor;
        }
      }
    }
  }
  • setAccessible(true)
    • 提高Java反射速度2
    • Accessable属性是继承自AccessibleObject 类. 功能是启用或禁用安全检查3

canAccessPrivateMethods() 私有方法访问权限判断

  /**
   * 对于类中私有方法访问权限的检查
   * SecurityManager 安全管理器检查是否
   * 允许取消由反射对象在其使用点上执行的标准 Java 语言访问检查
   * 对于 public、default(包)访问、protected、private 成员
   * @return
   */
  private static boolean canAccessPrivateMethods() {
    try {
      SecurityManager securityManager = System.getSecurityManager();
      if (null != securityManager) {
        securityManager.checkPermission(new ReflectPermission("suppressAccessChecks"));
      }
    } catch (SecurityException e) {
      return false;
    }
    return true;
  }
  • SecurityManager
    • 安全管理器是一个允许应用程序实现安全策略的类。它允许应用程序在执行一个可能不安全或敏感的操作前确定该操作是什么,以及是否是在允许执行该操作的安全上下文中执行它。应用程序可以允许或不允许该操作
  • checkPermission(new ReflectPermission("suppressAccessChecks"));
    • ReflectPermission4 是一种指定权限,没有操作。当前定义的惟一名称是 suppressAccessChecks,它允许取消由反射对象在其使用点上执行的标准 Java 语言访问检查 - 对于 public、default(包)访问、protected、private 成员

单元测试

// 被反射的类需有默认的构造方法
public class GoodsPO {

    /**
     * 商品编号
     */
    private Integer goodsId ;

    /**
     * 商品编号
     */
    private String goodsSn ;

    /**
     * 商品库存
     */
    private Integer goodsStock ;

    /**
     * 商品图片
     */
    private String goodsImg ;

    public GoodsPO(Integer goodsId, String goodsSn, Integer goodsStock, String goodsImg) {
        this.goodsId = goodsId;
        this.goodsSn = goodsSn;
        this.goodsStock = goodsStock;
        this.goodsImg = goodsImg;
    }
}

// 类中无默认构造方法,此时抛出异常
public class ReflectorMain {

    public static void main(String[] args) {
        Reflector reflector = new Reflector(GoodsPO.class);
        System.out.println(reflector.getDefaultConstructor());
    }
}

Exception in thread “main” org.apache.ibatis.reflection.ReflectionException: There is no default constructor for class


addGetMethods() 添加可读方法

  /**
   * 添加属性及其对应的可读方法 getXXX() / isXXX()
   * @param cls
   */
  private void addGetMethods(Class<?> cls) {
    // 属性及其对应的可读方法集合映射
    // 可读属性方法为集合的原因在于子类会重写覆盖父类的可读方法
    // 父类 List getX() 子类 ArrayList getX() 
    // 但是属性只会有一个最终的可读方法,此处是为了记录冲突
    Map<String, List<Method>> conflictingGetters = new HashMap<String, List<Method>>();
    // 当前类中的所有方法
    Method[] methods = getClassMethods(cls);
    for (Method method : methods) {
      String name = method.getName();
      if (name.startsWith("get") && name.length() > 3) {
        if (method.getParameterTypes().length == 0) {
          name = PropertyNamer.methodToProperty(name);
          addMethodConflict(conflictingGetters, name, method);
        }
      } else if (name.startsWith("is") && name.length() > 2) {
        if (method.getParameterTypes().length == 0) {
          name = PropertyNamer.methodToProperty(name);
          addMethodConflict(conflictingGetters, name, method);
        }
      }
    }
    resolveGetterConflicts(conflictingGetters);
  }

  • getClassMethods() 获取类中所有方法
  /*
   * This method returns an array containing all methods
   * declared in this class and any superclass.
   * We use this method, instead of the simpler Class.getMethods(),
   * because we want to look for private methods as well.
   *
   * @param cls The class
   * @return An array containing all methods in this class
   */
  private Method[] getClassMethods(Class<?> cls) {
  // 方法的唯一标识与方法的映射关系集合
    Map<String, Method> uniqueMethods = new HashMap<String, Method>();
    Class<?> currentClass = cls;
    while (currentClass != null) {
      // declaredMethods只能获取当前类的方法(包访问权限+public + private + protcted)
      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) {
        // getMethods可以获取本身类和其所有父类的所有共有方法(public)
        // 接口中定义的方法默认访问权限为 public ,所以只需获取接口及接口父类中的共有方法
        addUniqueMethods(uniqueMethods, anInterface.getMethods());
      }
      // 遍历当前类及父类中的方法,逐级向上查找
      // Object 是所有类的父类
      // Object 本身没有父类,为null
      currentClass = currentClass.getSuperclass();
    }

    Collection<Method> methods = uniqueMethods.values();

    return methods.toArray(new Method[methods.size()]);
  }

  • Class 中获取声明的方法5
    • getDeclaredMethods():只能获取当前类的方法(包访问权限+public + private + protcted)
    • getMethods():本身类和其**所有父类的所有共有(public)方法
  • Class 中获取接口的方法
    • getInterfaces()6
      • 若此对象表示一个类,返回该类实现的接口 implements
      • 若此对象标识一接口,返回接口继承的接口 extends

addUniqueMethods()

  private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) {
    for (Method currentMethod : methods) {
      // 当前方法非桥接方法
      if (!currentMethod.isBridge()) {
        // 方法唯一标识
        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)) {
          if (canAccessPrivateMethods()) {
            try {
              currentMethod.setAccessible(true);
            } catch (Exception e) {
              // Ignored. This is only a final precaution, nothing we can do.
            }
          }

          uniqueMethods.put(signature, currentMethod);
        }
      }
    }
  }
  • currentMethod.isBridge()7桥接方法
    • 出现节点:当父类中存在泛型接口,子类中用具体数据类型重写覆盖父类中的方法时
    • 出现原因:
      • 编译器在编译泛型接口时会将泛型擦除
        	List<T> list = new ArrayList<>() 
        	// 变为
        	List list = new ArrayList<>(); 	
        
      • 父类擦除泛型后编译结果变为 List<Object>
      • 但子类中存在的是 List<String> 泛型的具体数据类型,子类没有覆盖重写父类中的方法,不符合规范定义;
      • 为了向前兼容,默认为子类添加 List<String> 的方法,此为桥接方法

getSignature() 获取方法标识

  /**
   * 方法的唯一标识
   * 格式:方法返回值类型名称#方法名称:方法参数名称列表
   * @param method
   * @return
   */
  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();
  }


/**
 *    Copyright 2009-2016 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.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

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.
 *
 * @author Clinton Begin
 */
public class Reflector {






  /**
   * 解决发生冲突的属性方法
   * 查到子类的方法并返回
   * @param conflictingGetters
   */
  private void resolveGetterConflicts(Map<String, List<Method>> conflictingGetters) {
    for (String propName : conflictingGetters.keySet()) {
      List<Method> getters = conflictingGetters.get(propName);
      Iterator<Method> iterator = getters.iterator();
      Method firstMethod = iterator.next();
      if (getters.size() == 1) {
        addGetMethod(propName, firstMethod);
      } else {
        Method getter = firstMethod;
        Class<?> getterType = firstMethod.getReturnType();
        while (iterator.hasNext()) {
          Method method = iterator.next();
          Class<?> methodType = method.getReturnType();
          if (methodType.equals(getterType)) {
            throw new ReflectionException("Illegal overloaded getter method with ambiguous type for property "
                + propName + " in class " + firstMethod.getDeclaringClass()
                + ".  This breaks the JavaBeans " + "specification and can cause unpredicatble results.");
          } else if (methodType.isAssignableFrom(getterType)) {
            // methodType 是 getterType 的父类
            // OK getter type is descendant
          } else if (getterType.isAssignableFrom(methodType)) {
            getter = method;
            getterType = methodType;
            // 返回子类中的方法
          } else {
            throw new ReflectionException("Illegal overloaded getter method with ambiguous type for property "
                + propName + " in class " + firstMethod.getDeclaringClass()
                + ".  This breaks the JavaBeans " + "specification and can cause unpredicatble results.");
          }
        }
        addGetMethod(propName, getter);
      }
    }
  }

  private void addGetMethod(String name, Method method) {
    if (isValidPropertyName(name)) {
      // 对 method 对象进行封装:适配器设计模式
      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<String, List<Method>>();
    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);
  }

  /**
   * 解决同一个属性对应多个属性方法
   * 举例:子类重写了父类中的方法且修改了返回值类型,此时方法签名不同
   * 父类:List<String> getA() , 方法签名为  java.util.List#getA </>
   * 子类:ArrayList<String> getA() , 方法签名为  java.util.ArrayList#getA </>
   * 同一个方法对应两个不同的签名,但两个签名实质依然是同一个方法
   * @param conflictingMethods
   * @param name
   * @param method
   */
  private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name, Method method) {
    List<Method> list = conflictingMethods.get(name);
    if (list == null) {
      list = new ArrayList<Method>();
      conflictingMethods.put(name, list);
    }
    list.add(method);
  }

  /**
   * 解决可写方法中方法签名冲突并写入可写方法集合及可写参数类型集合
   * @param conflictingSetters
   */
  private void resolveSetterConflicts(Map<String, List<Method>> conflictingSetters) {
    for (String propName : conflictingSetters.keySet()) {
      List<Method> setters = conflictingSetters.get(propName);
      Method firstMethod = setters.get(0);
      if (setters.size() == 1) {
        addSetMethod(propName, firstMethod);
      } else {
        Class<?> expectedType = getTypes.get(propName);
        if (expectedType == null) {
          throw new ReflectionException("Illegal overloaded setter method with ambiguous type for property "
              + propName + " in class " + firstMethod.getDeclaringClass() + ".  This breaks the JavaBeans " +
              "specification and can cause unpredicatble results.");
        } else {
          Iterator<Method> methods = setters.iterator();
          Method setter = null;
          while (methods.hasNext()) {
            Method method = methods.next();
            if (method.getParameterTypes().length == 1
                && expectedType.equals(method.getParameterTypes()[0])) {
              setter = method;
              break;
            }
          }
          if (setter == null) {
            throw new ReflectionException("Illegal overloaded setter method with ambiguous type for property "
                + propName + " in class " + firstMethod.getDeclaringClass() + ".  This breaks the JavaBeans " +
                "specification and can cause unpredicatble results.");
          }
          addSetMethod(propName, setter);
        }
      }
    }
  }

  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((Class<?>) componentClass, 0).getClass();
      }
    }
    if (result == null) {
      result = Object.class;
    }
    return result;
  }

  private void addFields(Class<?> clazz) {
    Field[] fields = clazz.getDeclaredFields();
    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())) {
          // 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();
          // 过滤 final 及 static 修饰的属性
          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));
    }
  }

  /**
   * 是否是有效的属性名称
   * 1.不以 $ 开头的属性名称
   * @param name
   * @return
   */
  private boolean isValidPropertyName(String name) {
    return !(name.startsWith("$") || "serialVersionUID".equals(name) || "class".equals(name));
  }






  /*
   * 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 propery 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 propery 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 writeable properties for an object
   *
   * @return The array
   */
  public String[] getSetablePropertyNames() {
    return writeablePropertyNames;
  }

  /*
   * Check to see if a class has a writeable property by name
   *
   * @param propertyName - the name of the property to check
   * @return True if the object has a writeable 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));
  }
}

/**
 *    Copyright 2009-2015 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.property;

import java.util.Locale;

import org.apache.ibatis.reflection.ReflectionException;

/**
 * @author Clinton Begin
 */
public final class PropertyNamer {

  private PropertyNamer() {
    // Prevent Instantiation of Static Class
  }

  /**
   * 由方法名称获取属性方法名称
   * 属性方法名称需要以 get set is 开头
   * @param name
   * @return
   */
  public static String methodToProperty(String name) {
    if (name.startsWith("is")) {
      name = name.substring(2);
    } else if (name.startsWith("get") || name.startsWith("set")) {
      name = name.substring(3);
    } else {
      throw new ReflectionException("Error parsing property name '" + name + "'.  Didn't start with 'is', 'get' or 'set'.");
    }
    // 驼峰式命令规则
    // 如果是一个单词 a --> getA() , 将 A 改为 a
    // 如果是多个单词 userName --> getUserName() , 属性名称中第二个字符为小写时, 将第一个字符小写 , 变为 userName
    if (name.length() == 1 || (name.length() > 1 && !Character.isUpperCase(name.charAt(1)))) {
      name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
    }

    return name;
  }

  public static boolean isProperty(String name) {
    return name.startsWith("get") || name.startsWith("set") || name.startsWith("is");
  }

  public static boolean isGetter(String name) {
    return name.startsWith("get") || name.startsWith("is");
  }

  public static boolean isSetter(String name) {
    return name.startsWith("set");
  }

}

/**
 *    Copyright 2009-2015 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.invoker;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Clinton Begin
 */
public class MethodInvoker implements Invoker {

  private Class<?> type;
  private Method method;

    /**
     * 适配器模式
     * 对象适配器模式,在Invoker实现类中关联 Method 对象
     * @param method
     */
  public MethodInvoker(Method method) {
    this.method = method;

    // 可写方法,setXXX() 参数只有一个
    if (method.getParameterTypes().length == 1) {
      type = method.getParameterTypes()[0];
    } else {
        // 可读方法,getXXX() / isXXX() 方法无参数
      type = method.getReturnType();
    }
  }

  @Override
  public Object invoke(Object target, Object[] args) throws IllegalAccessException, InvocationTargetException {
    return method.invoke(target, args);
  }

  @Override
  public Class<?> getType() {
    return type;
  }
}


源码注解

  • constructor.setAccessible(true)

    • 功能:提供了将反射的对象标记为在使用时取消默认 Java 语言访问控制检查的能力
    • 作用:安全检查耗时很长,通过此处的设置可以提高反射速度4
  • isAssignableFrom8

    • isAssignableFrom()方法是从类继承的角度去判断,instanceof关键字是从实例继承的角度去判断。
    • isAssignableFrom()方法是判断是否为某个类的父类,instanceof关键字是判断是否某个类的子类。
  • Method

    • java.lang.reflect.Method.getGenericReturnType()9
      • 返回:方法返回一个Type对象,该对象表示此Method对象表示的方法的正式返回类型
    • java.lang.reflect.Method.getDeclaringClass()10
      • 返回:声明由此Method对象表示的方法的类的Class对象
  • Class

    • Class 对象表示 JVM 中的一个类或接口,每个Java 类在JVM中都表示为一个 Class 对象
    • 所有的类都是在对其第一次使用时,动态加载到JVM中的(懒加载)11

源码分析

  • 构造方法:public Reflector(Class<?> clazz)
    • 入参为欲反射的类的Class对象信息
  • 默认构造方法:addDefaultConstructor(clazz);
    • 遍历当前类中所有的构造方法,查询参数数量为0的默认构造方法
    • 此处需要注意默认构造方法是系统默认添加的,如果显示添加构造方法则不会默认生成无参构造方法

源码测试

  • Method 主要方法单元测试
package com.mybatis.reflect;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Method 主要方法测试类
 */
public class ReflectMethodTest {

    private Integer id ;

    private String name ;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getIdNum(){
        return id ;
    }

    public List<Integer> getIdList(){
        return Arrays.asList(id);
    }

    public Map<Integer,String> getIdNameMap(){
        Map<Integer,String> map = new HashMap<Integer, String>();
        map.put(id,name);
        return map;
    }

    public Integer[] getIdArray(){
        return new Integer[]{id};
    }

    @Override
    public String toString(){
        return "1" ;
    }

    public static void main(String[] args) {
        Method[] methods = ReflectMethodTest.class.getMethods();
        for (Method method : methods) {
            // 正式的返回值类型即
            // 基本数据类型:int --> int
            // 引用数据类型:
            // 类  :String                   --> class java.lang.String
            // 集合:List<Integer>            --> java.util.List<java.lang.Integer>
            // 容器:Map<Integer,String>      --> java.util.Map<java.lang.Integer, java.lang.String>
            // 数组:Integer[]                --> class [Ljava.lang.Integer;
            System.out.println("方法名称:" + method.getName() + ",正式返回值的类型:" + method.getGenericReturnType());
            // 返回方法所在的类
            // 子类覆盖重写父类方法,只返回子类
            System.out.println("方法名称:" + method.getName() + ",方法的类的Class对象:" + method.getDeclaringClass());
        }
    }

}


  1. 设计模式 | 适配器模式及典型应用 ↩︎

  2. 提高java反射速度的方法method.setAccessible(true) ↩︎

  3. java反射field.setAccessible()方法作用 ↩︎

  4. 类 ReflectPermission ↩︎ ↩︎

  5. Java中Class的getDeclaredMethods和getMethods的区别 ↩︎

  6. Class的getInterfaces与getGenericInterface区别 ↩︎

  7. java中什么是bridge method(桥接方法) ↩︎

  8. java中isAssignableFrom()方法与instanceof关键字用法及通过反射配合注解为字段设置默认值 ↩︎

  9. java.lang.reflect.Method.getGenericReturnType()方法示例 ↩︎

  10. java.lang.reflect.Method.getDeclaringClass()方法示例 ↩︎

  11. Class类简介 ↩︎

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值