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

基於Mybatis-3.5.0版本java

1.0 Reflector反射器

org.apache.ibatis.reflection.Reflector反射器,每一個Reflector對應一個類,會緩存反射操做須要的類的元數據,例如:構造方法、屬性名、get/set方法等等。代碼以下:apache

/** * 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對象,並提供了緩存功能。代碼以下:數組

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方法
默認方法使得開發者能夠在不破壞二進制兼容性的前提下,往現存接口中添加新的方法,即不強制那些實現了該接口的類也同時實現這個新加的方法。app

computeIfAbsent方法爲Map類下面的默認方法,代碼以下:ide

//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()由來,含義和使用場景ui

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的差別:this

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

例:spa

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必定會有一些莫名其妙的問題

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

相關文章
相關標籤/搜索