ParameterizedType,TypeVariable,GenericArrayType,WildcardType

public interface Type是 Java 编程语言中所有类型的公共高级接口。它包括:

  • 原始类型:一般意义上的java类,由class类实现(Class<?>)
  • 参数化类型:ParameterizedType接口的实现类
  • 数组类型:GenericArrayType接口的实现类
  • 类型变量:TypeVariable接口的实现类
  • 基本类型:int,float等java基本类型,其实也是Class<?>

这些子接口的特性可以在如下单元测试中获得:

public class TypeTest {
	static class Model<T> {
		String s;
		List<String> list;
		T[] array;
		T t;
		Class<? extends Number> num;
	}
	
	@Test
	public void theClass() throws NoSuchFieldException, SecurityException {
		Field f = Model.class.getDeclaredField("s");
		Type type = f.getGenericType();
		assertTrue(type instanceof Class<?>);
	}
	
	@Test
	public void theParameterizedType() throws NoSuchFieldException, SecurityException {
		Field f = Model.class.getDeclaredField("list");
		Type type = f.getGenericType();
		assertTrue(type instanceof ParameterizedType);
                ParameterizedType parameterizedType = (ParameterizedType)type;
		assertEquals(String.class, parameterizedType.getActualTypeArguments()[0]);
	}
	
	@Test
	public void theGenericArrayType() throws NoSuchFieldException, SecurityException {
		Field f = Model.class.getDeclaredField("array");
		Type type = f.getGenericType();
		assertTrue(type instanceof GenericArrayType);
	}
	
	@Test
	public void theTypeVariable() throws NoSuchFieldException, SecurityException {
		Field f = Model.class.getDeclaredField("t");
		Type type = f.getGenericType();
		assertTrue(type instanceof TypeVariable);
		TypeVariable typeVariable = (TypeVariable)type;
		assertEquals(1, typeVariable.getBounds().length);
		assertEquals(Model.class, typeVariable.getGenericDeclaration());
		assertEquals(Object.class, typeVariable.getBounds()[0]);
		assertEquals("T", typeVariable.getTypeName());
	}
	
	@Test
	public void theWildcardType() throws NoSuchFieldException, SecurityException {
		Field f = Model.class.getDeclaredField("num");
		Type type = f.getGenericType();
		assertTrue(type instanceof ParameterizedType);
		ParameterizedType parameterizedType = (ParameterizedType) type;
		Type subType = parameterizedType.getActualTypeArguments()[0];
		assertTrue(subType instanceof WildcardType);
		WildcardType wildcardType = (WildcardType) subType;
		assertEquals("? extends java.lang.Number", wildcardType.getTypeName());
		Type[] upperBounds = wildcardType.getUpperBounds();
		Type[] lowerBounds = wildcardType.getLowerBounds();
		assertEquals(1, upperBounds.length);
		assertEquals(0, lowerBounds.length);
		assertEquals(Number.class, upperBounds[0]);
	}
}

posted @ 2020-11-24 20:08  ralgo  阅读(339)  评论(0)    收藏  举报