Mybatis技術內幕(2.3.7):反射模組-TypeParameterResolver

失控的阿甘發表於2019-04-02

基於Mybatis-3.5.0版本

Type 介面

  為什麼要單獨拿一篇文章來講呢?因為裡面涉及到的java-Type介面的內容之前沒有接觸和了解過。我相信在座的很多小夥伴也一定不知道其中的奧祕哦~
  你知道Class物件還有一個父介面嗎?

以下內容均摘錄自 徐郡明 《Mybatis技術內幕》

先簡單介紹一下Type介面的基礎知識。Type是所有型別的父介面,它有四個子介面和一個實現類,如下圖:

Mybatis技術內幕(2.3.7):反射模組-TypeParameterResolver

下面來看這些子介面和子類所代表的型別

  • Class比較常見,它表示的是原始型別。Class類的物件表示JVM中的一個類或者介面,每個java類在JVM裡都表現為一個Class物件。在程式中可以通過“型別.class”、“物件.getClas()”或是“Class.forName("類名")”等方法獲取Class物件。陣列也被對映為Class物件,所有元素相同且維數相同的陣列都共享同一個Class物件。
  • ParameterizedType表示的是引數化型別,例如List<String>、Map<Integer,String>、Service<User>這種帶有泛型的型別。ParameterizedType介面中常用的方法有三個,分別是:
    • Type getRawType()——返回引數化型別中的原始型別。例如List<String>的原始型別為List
    • Type[] getActualTypeArguments()——獲取引數化型別的型別變數或是實際型別列表。例如Map<Integer,String>的實際泛型列表Integer和String。需要注意的是,該列表的型別都是Type,也就是說,可能存在多層巢狀的情況。
    • Type getOwnerType()——返回的是型別所屬的型別,例如存在A<T>類,其中定義了內部類InnerA<T>,則Inner<A>所屬的型別A<T>,如果是頂層型別則返回null。這種關係比較常見的示例是Map<K,V>介面與Map.Entry<K,V>介面,Map<K,V>介面是Map.Entry<K,V>介面的所有者
  • TypeVariable表示的是型別變數,它用來反映在JVM編譯該泛型前的資訊。例如List<T>中T就是型別變數,它在編譯是需被轉換為一個具體的型別後才能正常使用。
    • Type[] getBounds()——獲取型別變數的上邊界,如果未明確宣告上邊界則預設為Object。例如class Test<K extends Person>中K的上界就是Person。
    • D getGenericDeclaration()——獲取宣告該型別變數的原始型別,例如class Test<K extends Person>中的原始型別是Test。
    • String getName()——獲取在原始碼中定義時的名字,上例中為K。
  • GenericArrayType表示的是陣列型別且組成的元素是ParameterizedType或TypeVariable。例如List<String>[]或T[]。該介面只有Type getGenericComponentType()一個方法,它返回陣列的組成元素。
  • WildcardType表示萬用字元泛型,例如? extends Number和? super Integer。
    • Type[] getUpperBounds()破折號泛型變數的上界。
    • Type[] getLowerBounds()破折號泛型變數的下界。

1.0 TypeParameterResolver

org.apache.ibatis.reflection.TypeParameterResolver是一個主要用來負責解析欄位型別、方法返回值型別和方法引數列表中各個引數的型別的一個工具類。程式碼如下:

/**
 * 暴露了三個公用靜態方法,分別用於解析Field型別、Method返回型別、方法引數型別
 * @author Iwao AVE!
 */
public class TypeParameterResolver {

	/**
	 * 解析屬性型別
	 * @return The field type as {@link Type}. If it has type parameters in the
	 *         declaration,<br>
	 *         they will be resolved to the actual runtime {@link Type}s.
	 */
	public static Type resolveFieldType(Field field, Type srcType) {
		// 屬性型別
		Type fieldType = field.getGenericType();
		// 定義的類
		Class<?> declaringClass = field.getDeclaringClass();
		// 解析型別
		return resolveType(fieldType, srcType, declaringClass);
	}

	/**
	 * 解析方法返回值型別
	 * @return The return type of the method as {@link Type}. If it has type
	 *         parameters in the declaration,<br>
	 *         they will be resolved to the actual runtime {@link Type}s.
	 */
	public static Type resolveReturnType(Method method, Type srcType) {
		// 返回值型別
		Type returnType = method.getGenericReturnType();
		// 定義的類
		Class<?> declaringClass = method.getDeclaringClass();
		// 解析型別
		return resolveType(returnType, srcType, declaringClass);
	}

	/**
	 * 解析方法引數型別
	 * @return The parameter types of the method as an array of {@link Type}s. If
	 *         they have type parameters in the declaration,<br>
	 *         they will be resolved to the actual runtime {@link Type}s.
	 */
	public static Type[] resolveParamTypes(Method method, Type srcType) {
		// 引數型別
		Type[] paramTypes = method.getGenericParameterTypes();
		// 定義的類
		Class<?> declaringClass = method.getDeclaringClass();
		Type[] result = new Type[paramTypes.length];
		for (int i = 0; i < paramTypes.length; i++) {
			// 解析型別
			result[i] = resolveType(paramTypes[i], srcType, declaringClass);
		}
		return result;
	}

	/**
	 * 解析型別
	 * @param type           型別
	 * @param srcType        來源型別
	 * @param declaringClass 定義的類
	 * @return 解析後的型別
	 */
	private static Type resolveType(Type type, Type srcType, Class<?> declaringClass) {
		if (type instanceof TypeVariable) {// 解析TypeVariable
			return resolveTypeVar((TypeVariable<?>) type, srcType, declaringClass);
		} else if (type instanceof ParameterizedType) {// 解析ParameterizedType
			return resolveParameterizedType((ParameterizedType) type, srcType, declaringClass);
		} else if (type instanceof GenericArrayType) {// 解析GenericArrayType
			return resolveGenericArrayType((GenericArrayType) type, srcType, declaringClass);
		} else {
			return type;// Class型別直接返回
		}
	}

	private static Type resolveGenericArrayType(GenericArrayType genericArrayType, Type srcType,
			Class<?> declaringClass) {
		Type componentType = genericArrayType.getGenericComponentType();
		Type resolvedComponentType = null;
		if (componentType instanceof TypeVariable) {
			resolvedComponentType = resolveTypeVar((TypeVariable<?>) componentType, srcType, declaringClass);
		} else if (componentType instanceof GenericArrayType) {
			resolvedComponentType = resolveGenericArrayType((GenericArrayType) componentType, srcType, declaringClass);
		} else if (componentType instanceof ParameterizedType) {
			resolvedComponentType = resolveParameterizedType((ParameterizedType) componentType, srcType,
					declaringClass);
		}
		if (resolvedComponentType instanceof Class) {
			return Array.newInstance((Class<?>) resolvedComponentType, 0).getClass();
		} else {
			return new GenericArrayTypeImpl(resolvedComponentType);
		}
	}

	/**
	 * 解析 ParameterizedType 型別
	 * @param parameterizedType ParameterizedType 型別
	 * @param srcType           來源型別
	 * @param declaringClass    定義的類
	 * @return 解析後的型別
	 */
	private static ParameterizedType resolveParameterizedType(ParameterizedType parameterizedType, Type srcType,
			Class<?> declaringClass) {
		Class<?> rawType = (Class<?>) parameterizedType.getRawType();
		// 解析 <> 中實際型別
		Type[] typeArgs = parameterizedType.getActualTypeArguments();
		Type[] args = new Type[typeArgs.length];
		for (int i = 0; i < typeArgs.length; i++) {
			if (typeArgs[i] instanceof TypeVariable) {
				args[i] = resolveTypeVar((TypeVariable<?>) typeArgs[i], srcType, declaringClass);
			} else if (typeArgs[i] instanceof ParameterizedType) {
				args[i] = resolveParameterizedType((ParameterizedType) typeArgs[i], srcType, declaringClass);
			} else if (typeArgs[i] instanceof WildcardType) {
				args[i] = resolveWildcardType((WildcardType) typeArgs[i], srcType, declaringClass);
			} else {
				args[i] = typeArgs[i];
			}
		}
		return new ParameterizedTypeImpl(rawType, null, args);
	}

	private static Type resolveWildcardType(WildcardType wildcardType, Type srcType, Class<?> declaringClass) {
		Type[] lowerBounds = resolveWildcardTypeBounds(wildcardType.getLowerBounds(), srcType, declaringClass);
		Type[] upperBounds = resolveWildcardTypeBounds(wildcardType.getUpperBounds(), srcType, declaringClass);
		return new WildcardTypeImpl(lowerBounds, upperBounds);
	}

	private static Type[] resolveWildcardTypeBounds(Type[] bounds, Type srcType, Class<?> declaringClass) {
		Type[] result = new Type[bounds.length];
		for (int i = 0; i < bounds.length; i++) {
			if (bounds[i] instanceof TypeVariable) {
				result[i] = resolveTypeVar((TypeVariable<?>) bounds[i], srcType, declaringClass);
			} else if (bounds[i] instanceof ParameterizedType) {
				result[i] = resolveParameterizedType((ParameterizedType) bounds[i], srcType, declaringClass);
			} else if (bounds[i] instanceof WildcardType) {
				result[i] = resolveWildcardType((WildcardType) bounds[i], srcType, declaringClass);
			} else {
				result[i] = bounds[i];
			}
		}
		return result;
	}

	/**
	 * 解析TypeVariable型別
	 * @param typeVar
	 * @param srcType
	 * @param declaringClass
	 * @return
	 */
	private static Type resolveTypeVar(TypeVariable<?> typeVar, Type srcType, Class<?> declaringClass) {
		Type result = null;
		Class<?> clazz = null;
		if (srcType instanceof Class) {
			clazz = (Class<?>) srcType;
		} else if (srcType instanceof ParameterizedType) {
			ParameterizedType parameterizedType = (ParameterizedType) srcType;
			clazz = (Class<?>) parameterizedType.getRawType();
		} else {
			throw new IllegalArgumentException(
					"The 2nd arg must be Class or ParameterizedType, but was: " + srcType.getClass());
		}

		if (clazz == declaringClass) {
			Type[] bounds = typeVar.getBounds();
			if (bounds.length > 0) {
				return bounds[0];
			}
			return Object.class;
		}

		Type superclass = clazz.getGenericSuperclass();
		result = scanSuperTypes(typeVar, srcType, declaringClass, clazz, superclass);
		if (result != null) {
			return result;
		}

		Type[] superInterfaces = clazz.getGenericInterfaces();
		for (Type superInterface : superInterfaces) {
			result = scanSuperTypes(typeVar, srcType, declaringClass, clazz, superInterface);
			if (result != null) {
				return result;
			}
		}
		return Object.class;
	}

	private static Type scanSuperTypes(TypeVariable<?> typeVar, Type srcType, Class<?> declaringClass, Class<?> clazz,
			Type superclass) {
		if (superclass instanceof ParameterizedType) {
			ParameterizedType parentAsType = (ParameterizedType) superclass;
			Class<?> parentAsClass = (Class<?>) parentAsType.getRawType();
			TypeVariable<?>[] parentTypeVars = parentAsClass.getTypeParameters();
			if (srcType instanceof ParameterizedType) {
				parentAsType = translateParentTypeVars((ParameterizedType) srcType, clazz, parentAsType);
			}
			if (declaringClass == parentAsClass) {
				for (int i = 0; i < parentTypeVars.length; i++) {
					if (typeVar == parentTypeVars[i]) {
						return parentAsType.getActualTypeArguments()[i];
					}
				}
			}
			if (declaringClass.isAssignableFrom(parentAsClass)) {
				return resolveTypeVar(typeVar, parentAsType, declaringClass);
			}
		} else if (superclass instanceof Class && declaringClass.isAssignableFrom((Class<?>) superclass)) {
			return resolveTypeVar(typeVar, superclass, declaringClass);
		}
		return null;
	}

	private static ParameterizedType translateParentTypeVars(ParameterizedType srcType, Class<?> srcClass,
			ParameterizedType parentType) {
		Type[] parentTypeArgs = parentType.getActualTypeArguments();
		Type[] srcTypeArgs = srcType.getActualTypeArguments();
		TypeVariable<?>[] srcTypeVars = srcClass.getTypeParameters();
		Type[] newParentArgs = new Type[parentTypeArgs.length];
		boolean noChange = true;
		for (int i = 0; i < parentTypeArgs.length; i++) {
			if (parentTypeArgs[i] instanceof TypeVariable) {
				for (int j = 0; j < srcTypeVars.length; j++) {
					if (srcTypeVars[j] == parentTypeArgs[i]) {
						noChange = false;
						newParentArgs[i] = srcTypeArgs[j];
					}
				}
			} else {
				newParentArgs[i] = parentTypeArgs[i];
			}
		}
		return noChange ? parentType
				: new ParameterizedTypeImpl((Class<?>) parentType.getRawType(), null, newParentArgs);
	}

	private TypeParameterResolver() {
		super();
	}

	static class ParameterizedTypeImpl implements ParameterizedType {
		private Class<?> rawType;

		private Type ownerType;

		private Type[] actualTypeArguments;

		public ParameterizedTypeImpl(Class<?> rawType, Type ownerType, Type[] actualTypeArguments) {
			super();
			this.rawType = rawType;
			this.ownerType = ownerType;
			this.actualTypeArguments = actualTypeArguments;
		}

		@Override
		public Type[] getActualTypeArguments() {
			return actualTypeArguments;
		}

		@Override
		public Type getOwnerType() {
			return ownerType;
		}

		@Override
		public Type getRawType() {
			return rawType;
		}

		@Override
		public String toString() {
			return "ParameterizedTypeImpl [rawType=" + rawType + ", ownerType=" + ownerType + ", actualTypeArguments="
					+ Arrays.toString(actualTypeArguments) + "]";
		}
	}

	static class WildcardTypeImpl implements WildcardType {
		private Type[] lowerBounds;

		private Type[] upperBounds;

		WildcardTypeImpl(Type[] lowerBounds, Type[] upperBounds) {
			super();
			this.lowerBounds = lowerBounds;
			this.upperBounds = upperBounds;
		}

		@Override
		public Type[] getLowerBounds() {
			return lowerBounds;
		}

		@Override
		public Type[] getUpperBounds() {
			return upperBounds;
		}
	}

	static class GenericArrayTypeImpl implements GenericArrayType {
		private Type genericComponentType;

		GenericArrayTypeImpl(Type genericComponentType) {
			super();
			this.genericComponentType = genericComponentType;
		}

		@Override
		public Type getGenericComponentType() {
			return genericComponentType;
		}
	}
}
複製程式碼

2.0 總結

  可以通過除錯org.apache.ibatis.reflection.TypeParameterResolverTest這個單元測試類,觸發不同的場景去深入瞭解Java-Type。   

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

相關文章