Mybatis技術內幕(2.3.1):反射模組-Reflector

失控的阿甘發表於2019-03-14

基於Mybatis-3.5.0版本

1.0 Reflector反射器

org.apache.ibatis.reflection.Reflector反射器,每個Reflector對應一個類,會快取反射操作需要的類的後設資料,例如:構造方法、屬性名、get/set方法等等。程式碼如下:

/**
 * 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 ReflectorFactory

org.apache.ibatis.reflection.ReflectorFactoryReflector工廠介面用於直接根據Class物件建立Reflector物件,並提供了快取功能。程式碼如下:

Mybatis技術內幕(2.3.1):反射模組-Reflector

public interface ReflectorFactory {
  boolean isClassCacheEnabled();

  void setClassCacheEnabled(boolean classCacheEnabled);

  Reflector findForClass(Class<?> type);
}
複製程式碼

2.1 DefaultReflectorFactory

org.apache.ibatis.reflection.DefaultReflectorFactory預設Reflector工廠介面實現類,程式碼如下:

public class DefaultReflectorFactory implements ReflectorFactory {
	// 是否開啟快取
	private boolean classCacheEnabled = true;
	/**
	 * ConcurrentMap 快取Reflector資訊 key:Class value:Class對應的Reflector
	 */
	private final ConcurrentMap<Class<?>, Reflector> reflectorMap = new ConcurrentHashMap<>();

	public DefaultReflectorFactory() {
	}

	@Override
	public boolean isClassCacheEnabled() {
		return classCacheEnabled;
	}

	@Override
	public void setClassCacheEnabled(boolean classCacheEnabled) {
		this.classCacheEnabled = classCacheEnabled;
	}

	/**
	 * 開啟快取:則直接從reflectorMap獲取,未獲取到則建立Reflector物件放入map並返回
	 * 未開啟快取:每次都建立新的Reflector物件
	 */
	@Override
	public Reflector findForClass(Class<?> type) {
		if (classCacheEnabled) {
			// synchronized (type) removed see issue #461
			return reflectorMap.computeIfAbsent(type, Reflector::new);
		} else {
			return new Reflector(type);
		}
	}
}
複製程式碼

3.0 整理學習的知識點

3.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);
	}
複製程式碼

3.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, "AAA");
	    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
複製程式碼

3.3 Class isAssignableFrom方法

isAssignableFrom 與 instanceof的差異:

  • isAssignableFrom 法是從類繼承的角度去判斷,判斷是否為某個類的父類
  • instanceof 是從例項繼承的角度去判斷,是判斷是否某個類的子類

例:

    List<String> list = new ArrayList<>();
	ArrayList.class.isAssignableFrom(List.class)// false
	list instanceof List // true
複製程式碼

4.0 總結

看完Reflector的程式碼,小菜阿甘有3個方面的感悟:

  • 1 大佬對java基礎認識很深刻,考慮問題非常全面
  • 2 方法命名和變數命名非常規範和直白(是這個原因導致註釋這麼少嗎o(╥﹏╥)o)
  • 3 大家平時在開發的過程中一定要有很好的規範,例如:如果大家javabean的getter或setter命名不規範,用Mybatis一定會有一些莫名其妙的問題

失控的阿甘,樂於分享,記錄點滴

相關文章