Mybatis技术内幕(2.3.1):反射模块-Reflector

基于Mybatis-3.5.0版本

org.apache.ibatis.reflection.Reflector
反射器,每个Reflector对应一个类,会缓存反射操作需要的类的元数据,例如:构造方法、属性名、get/set方法等等
大家可以跟着源码看下注释,再自己理解一下。代码如下:

  • Mybatis源码地址
  • 阿甘注释的源码

因为整个注释和学习源码的过程才刚刚开始,所以很多类的注释和分享还没有,请大家关注关注给个好评哦

/**
 *    Copyright 2009-2018 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.
 *
 * 反射器,每个 Reflector对应一个类, 会缓存类的元信息,
 * 此类表示一组缓存的类的元数据,允许在属性名和getter/setter方法之间轻松映射。
 * @author Clinton Begin
 */
public class Reflector {
	// 对应类的Class对象
	private final Class<?> type;
	// 可读属性数组
	private final String[] readablePropertyNames;
	// 可写属性数组
	private final String[] writeablePropertyNames;
	// key是属性名称,value是Invoker对象
	/**
	 * Invoker接口:适配器模式用于消除java bean的 
	 * getter方法、setter方法、Filed属性的set/get的操作差异
	 */
	private final Map<String, Invoker> setMethods = new HashMap<>();
	// key是属性名称,value是Invoker对象
	private final Map<String, Invoker> getMethods = new HashMap<>();
	// key是属性名称,value是setter方法的参数值类型
	private final Map<String, Class<?>> setTypes = new HashMap<>();
	// key是属性名称,value是getter方法的返回值类型
	private final Map<String, Class<?>> getTypes = new HashMap<>();
	// 默认无参构造器
	private Constructor<?> defaultConstructor;
	// 不区分大小写的属性集合 key:toUpperCase的属性名称 value:原属性名称
	private Map<String, String> caseInsensitivePropertyMap = new HashMap<>();

	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);
		}
	}

	/**
	 * 初始化defaultConstructor
	 * @param clazz
	 */
	private void addDefaultConstructor(Class<?> clazz) {
		// 获取所有声明的构造方法
		Constructor<?>[] consts = clazz.getDeclaredConstructors();
		for (Constructor<?> constructor : consts) {
			// 参数数量为0,即没有参数的构造方法为 默认构造方法
			if (constructor.getParameterTypes().length == 0) {
				this.defaultConstructor = constructor;
			}
		}
	}

	/**
	 * 初始化getMethods和getTypes
	 * @param cls
	 */
	private void addGetMethods(Class<?> cls) {
		// key:属性名称,value:getter方法集合
		/**
		 * 因为在java的继承关系中,会存在子类重写父类的方法,但是放大了返回值类型 所有会存在conflicting冲突的方法
		 * 例:
		 * super: List<String> getIds();
		 * sub: ArrayList<String> getIds();
		 */
		Map<String, List<Method>> conflictingGetters = new HashMap<>();
		// 获取所有方法
		Method[] methods = getClassMethods(cls);
		/**
		 * 循环添加规范的getter方法
		 * java bean getter规范:
		 * 1.没有参数
		 * 2.若以get开头,方法长度大于3
		 * 3.若以is开头,方法长度大于2
		 */
		for (Method method : methods) {
			if (method.getParameterTypes().length > 0) {
				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);
			}
		}
		// 解决冲突的方法,将最合适的方法添加到getMethods和getTypes
		resolveGetterConflicts(conflictingGetters);
	}

	/**
	 * 解决getter方法冲突,寻找最规范和最合理的getter方法
	 * 冲突原因:因为在java的继承关系中,会存在子类重写父类的方法,但是放大了返回值类型 所有会存在conflicting冲突的方法
	 * 例:
	 * super: List<String> getIds();
	 * sub: ArrayList<String> getIds();
	 * 
	 * @param conflictingGetters
	 */
	private void resolveGetterConflicts(Map<String, List<Method>> conflictingGetters) {
		for (Entry<String, List<Method>> entry : conflictingGetters.entrySet()) {
			Method winner = null;//胜利者 即最规范最合理的getter方法
			String propName = entry.getKey();
			for (Method candidate : entry.getValue()) {
				if (winner == null) {
					winner = candidate;
					continue;
				}
				/**
				 * 如果返回类型相同,不是boolean类型报异常,以is开头的方法为主 
				 * 主要解决Boolean类型属性,命名不规范 例: getFlag() 与  isFlag()
				 */
				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;
					}
				/**
				 * isAssignableFrom()方法是从类继承的角度去判断,判断是否为某个类的父类
				 * instanceof()方法是从实例继承的角度去判断,是判断是否某个类的子类。
				 * 以子类返回类型为主:针对一些重写的场景,子类放大了返回值
				 * 例如: 父类的一个方法的返回值为 List ,子类对该方法的返回值可以覆写为 ArrayList
				 */
				} 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);
		}
	}

	/**
	 * 缓存Getter方法和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));
		}
	}

	/**
	 * 初始化 setMethods和setTypes属性
	 * 整个流程和初始化Getter方法类似
	 * @param cls
	 */
	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);
	}

	/**
	 * java8 Map default computeIfAbsent方法 
	 * put key,存在则返回value,不存在创建value并put(key,vlue) 返回value
	 * @param conflictingMethods
	 * @param name
	 * @param method
	 */
	private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name, Method method) {
		List<Method> list = conflictingMethods.computeIfAbsent(name, k -> new ArrayList<>());
		list.add(method);
	}

	/**
	 * 解决Setter方法冲突,保证最规范在最合理的Setter方法
	 * @param conflictingSetters
	 */
	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];
				//setter对应的参数类型与该属性对应的getter的响应值类型一致则是合理的setter方法
				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;
	}

	/**
	 * 	初始化setMethods和setTypes属性和getMethods和getTypes属性
	 *	主要处理一些属性没有对应的getter和setter方法的情况
	 * @param clazz
	 */
	private void addFields(Class<?> clazz) {
		// 获取声明的属性对象
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			// setter缓存里面不存在的就处理
			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
				// 过滤掉final和static修饰的字段
				int modifiers = field.getModifiers();
				if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) {
					addSetField(field);
				}
			}
			// getter缓存里面不存在的就处理
			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
	 * 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) {
		// key:方法签名,value:Method方法
		Map<String, Method> uniqueMethods = new HashMap<>();
		Class<?> currentClass = cls;
		// 循环类,类的父类,类的父类的父类,直到父类为 Object
		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()]);
	}

	/**
	 * 添加方法签名唯一的方法
	 * @param uniqueMethods
	 * @param methods
	 */
	private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) {
		for (Method currentMethod : methods) {
			if (!currentMethod.isBridge()) {// bridge方法不处理
				// 获取方法签名
				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);
				}
			}
		}
	}

	/**
	 * 获取方法签名
	 * 格式:响应值类型名称方法名称:方法参数类型名称
	 * 例:
	 * void#setId:java.lang.Long
	 * @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();
	}

	/**
	 * 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;
	}

	/**
	 * 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 writeablePropertyNames;
	}

	/**
	 * 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));
	}
}
复制代码

2.0 整理学习的知识点

2.1 java8 Map computeIfAbsent

java8 新特性:default方法

默认方法使得开发者可以在 不破坏二进制兼容性
的前提下,往现存接口中添加新的方法,即不强制那些实现了该接口的类也同时实现这个新加的方法。

computeIfAbsent
方法为Map类下面的默认方法,代码如下:

//put key,存在则返回value,不存在创建value并put(key,vlue) 返回value
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
        Objects.requireNonNull(mappingFunction);
        V v;
        if ((v = get(key)) == null) {
            V newValue;
            if ((newValue = mappingFunction.apply(key)) != null) {
                put(key, newValue);
                return newValue;
            }
        }
        return v;
    }
复制代码

特别适用于一些value为集合类型的数据,可以看下Mybatis3.4.6版本和3.5.0版本的代码差异:

//3.5.0
private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name, Method method) {
		List<Method> list = conflictingMethods.computeIfAbsent(name, k -> new ArrayList<>());
		list.add(method);
	}

//3.4.6
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);
	}
复制代码

2.2 关于Method isBridge()

关于Method isBridge()方法,主要针对一些泛型方法,因为泛型擦除的原因,导致重载的方法失去意义,所以会在对应的类里面注入一个bridge方法,见下例: Java反射中method.isBridge()由来,含义和使用场景

interface A<T> {
	void func(T t);
}

class B implements A<String> {

	@Override
	public void func(String t) {
		System.out.println(t);
	}
}

public static void main(String[] args) throws Exception {
		B obj = new B();
	    Method func = B.class.getMethod("func", String.class);
	    func.invoke(obj, "BBB");
	    System.out.println(func.isBridge());
	    func = B.class.getMethod("func", Object.class);
	    func.invoke(obj, "BBB");
	    System.out.println(func.isBridge());
	}
	
console:
AAA
false
BBB
true
复制代码

2.3 Class isAssignableFrom方法

isAssignableFrom 与 instanceof的差异:

  • isAssignableFrom 法是从类继承的角度去判断,判断是否为某个类的父类
  • instanceof 是从实例继承的角度去判断,是判断是否某个类的子类

例:

List<String> list = new ArrayList<>();
	ArrayList.class.isAssignableFrom(List.class)// false
	list instanceof List // true
复制代码

原文 

https://juejin.im/post/5c89f6c65188257e16047b5e

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » Mybatis技术内幕(2.3.1):反射模块-Reflector

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址