ParameterizedType、GenericArrayType、TypeVariable中常用的方法
一、ParameterizedType
ParameterizedType 接口是 Java 中的一个类型接口,它用于表示带有泛型参数的类型,例如 List 或 Map<Integer, String> 等。通过 ParameterizedType 接口,我们可以获取泛型类型的实际参数类型信息,而不仅仅是泛型的类型变量。
- Type[] getActualTypeArguments(): 返回表示此类型实际类型参数的 Type 对象数组。
- Type getRawType(): 返回表示此类型的原始类型的 Type 对象。
- Type getOwnerType(): 返回表示此类型的所有者类型的 Type 对象。
1、方法详解
getActualTypeArguments()方法,例如 List ,Map<String,Long> 获取的是<>里面的参数,
public static final Map<String, Long> map = new HashMap<>();
public static void main( String[] args ) throws NoSuchMethodException, NoSuchFieldException {
Field field = App.class.getDeclaredField("map");
Type genericType = field.getGenericType();
if (genericType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericType;
Type[] actualTypeArguments = ((ParameterizedType) genericType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
结果为 获取到了<>里面的参数
class java.lang.String
class java.lang.Long
getRawType()表示此类型的原始类型的 Type 例如 Map<String,Long> 获取到的是map原始对象
public static final Map<String, Long> map = new HashMap<>();
public static void main( String[] args ) throws NoSuchMethodException, NoSuchFieldException {
Field field = App.class.getDeclaredField("map");
Type genericType = field.getGenericType();
if (genericType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericType;
System.out.println("getRawType:" + parameterizedType.getRawType());
}
}
结果Map<String,Long> 获取到了map原始对象
getRawType:interface java.util.Map
二、GenericArrayType
GenericArrayType在java中表示的是泛型数组,他表示带有泛型的数组,例如:String[]、E[]、ArrayList[]
-
getComponentType()只有这一个方法,方法的作用是,无论从左向右有几个[]并列,这个方法仅仅脱去最右边的之后剩下的内容就作为这个方法的返回值:
(1)对于String[],通过getComponentType()返回之后,脱去最右边的[]之后,剩余的类型是String。因此对这个参数的返回类型是Class (2)对于E[],通过getComponentType()返回之后,脱去最右边的[]之后,剩余的类型是E。因此对这个参数的返回类型是TypeVariable 对于ArrayList<E>[],通过getComponentType()返回之后,脱去最右边的[]之后,剩余的类型是ArrayList<E>。因此对这个参数的返回类型是ParameterizedType (3)对于E[][],通过getComponentType()返回之后,脱去最右边的[]之后,剩余的类型是E[]。因此对这个参数的返回类型是GenericArrayType
三、TypeVariable
表示类型参数或者又叫做类型变量。比如:void method(E e){}中的E就是类型变量.
- type[] getBounds 获得该类型变量的上限(上边界),若无显式定义(extends),默认为object,类型变量的上限可能不止一个,因为可以用&符号限定多个(这其中有且只能有一个为类或抽象类,且必须放在extends后的第一个,即若有多个上边界,则第一个&后必为接口)
1、方法详解
getBounds(方法) 可以看到我们定义了一个方法test 返回值类型是TypeVariable类型,调用getBounds方法
public static <T extends List> T test(T t) {
return t;
}
public static void main( String[] args ) throws NoSuchMethodException, NoSuchFieldException {
Method method = App.class.getMethod("test", List.class);
Type genericReturnType = method.getGenericReturnType();
if (genericReturnType instanceof TypeVariable) {
TypeVariable typeVariable = (TypeVariable) genericReturnType;
Type[] bounds = typeVariable.getBounds();
for (Type bound : bounds) {
System.out.println(bound);
}
}
}
结果为,成功的获取到了的上边界 list
interface java.util.List