泛型基本:5.0 泛型出现之后,Java Reflection API的新特点。首先增加一个接口java.lang.reflect.Type
java.lang.reflect.Type
|--------TypeVariable
|--------ParameterizedType
|--------GenericArrayType
|--------WildcardType
1)
TypeVariable:用来保存泛型
编译前的基本信息
- public class BaseOrder<M extends Object & Serializable,N extends Comparable<N>> implements IBaseOrder {
- public M getManufactory(){
- return manufactory;
- }
- }
主要是继承一个类,实现多个接口,getBounds去获取
- assertTrue("The type of field manufactory is an instance of TypeVariable", type instanceof TypeVariable);
- TypeVariable tType = (TypeVariable)type;
- assertEquals("The name of this TypeVariable is M", "M", tType.getName());
- assertEquals("The TypeVariable bounds two type", 2, tType.getBounds().length);
- assertEquals("One type of these bounds is Object", Object.class, tType.getBounds()[0]);
- assertEquals("And annother si Serializable", Serializable.class, tType.getBounds()[1]);
|
2)
ParameterizedType 带参的泛型,主要用于继承,获取泛型用
- public class Order
- extends BaseOrder<Customer, Long> implements IOrder, Serializable {
- }
- Type genericSuperclass = Order.class.getGenericSuperclass();
- assertTrue("Order's supper class is a type of ParameterizedType.", genericSuperclass instanceof ParameterizedType);
- ParameterizedType pType = (ParameterizedType)genericSuperclass;
- assertEquals("Order's supper class is BaseOrder.", BaseOrder.class, pType.getRawType());
- Type[] arguments = pType.getActualTypeArguments();
- assertEquals("getActualTypeArguments() method return 2 arguments.", 2, arguments.length);
- for (Type type : arguments) {
- Class clazz = (Class)type;
- if(!(clazz.equals(Customer.class)) && !(clazz.equals(Long.class))){
- assertTrue(false);
- }
- }
getGenericSuperclass :获取父类的泛型
getRawType() : 获取该泛型对应的设计类
getActualTypeArguments : 获取该泛型实际传入的类型
|
3)
GenericArrayType 泛型数组
- public String[] getPayments(String[] payments, List<Product> products){
- return payments;
- }
- Method getPayments = BaseOrder.class.getMethod("getPayments", new Class[]{String[].class, List.class});
- types = getPayments.getGenericParameterTypes();
- assertTrue("The first parameter of this method is GenericArrayType.", types[0] instanceof GenericArrayType);
- GenericArrayType gType = (GenericArrayType)types[0];
- assertEquals("The GenericArrayType's component is String.", String.class, gType.getGenericComponentType());
|
4)WildcardType 就是获取通配符泛型的信息
- private Comparable<? extends Customer> comparator;
- Field comparatorField = BaseOrder.class.getDeclaredField("comparator");
- ParameterizedType pType = (ParameterizedType)comparatorField.getGenericType();
- type = pType.getActualTypeArguments()[0];
- assertTrue("The type of field comparator is an instance of ParameterizedType, and the actual argument is an instance of WildcardType.", type instanceof WildcardType);
- WildcardType wType = (WildcardType)type;
- assertEquals("The upper bound of this WildcardType is Customer.", Customer.class, wType.getUpperBounds()[0]);
|
|