Java反射代码片断:你这个“类型”是哪种类型?

Class是哪种Class ?

clazz.isPrimitive(); //是否primitive type

//是否为primitive type的封装类?看看它在不在下面的map里(这个map节选自spring的ClassUtils.java)

      primitiveWrapperTypeMap.put(Boolean.class, boolean.class);
      primitiveWrapperTypeMap.put(Byte.class, byte.class);
      primitiveWrapperTypeMap.put(Character.class, char.class);
      primitiveWrapperTypeMap.put(Double.class, double.class);
      primitiveWrapperTypeMap.put(Float.class, float.class);
      primitiveWrapperTypeMap.put(Integer.class, int.class);
      primitiveWrapperTypeMap.put(Long.class, long.class);
      primitiveWrapperTypeMap.put(Short.class, short.class);


clazz.isArray(); //是否为数组类型

拿到的是java.lang.reflect.Type类型,它是哪种Type ?

if (javaReflectType instanceof ParameterizedType); //是否为泛型
if (javaReflectType instanceof Class) //是否为类

是哪种泛型

ParameterizedType pt = (ParameterizedType) javaReflectType;
Type rawType = pt.getRawType(); //尖括号前面的类型,如List<String>中的List

//Collection<SomeClass> 
if (Collection.class.isAssignableFrom(rawClass)) {
    Type type = pt.getActualTypeArguments()[0]; //类集中的元素类型
}

//Map<KeyClass, ValueClass>
if (Map.class.isAssignableFrom(rawClass)) {
                  Type keyType = pt.getActualTypeArguments()[0];  //Map中的key类型
                  Type valueType = pt.getActualTypeArguments()[1];//Map中的value类型
}

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.