在 java 中,Type 是所有类型的公共接口。它有以下几个子类:
Class , GenericArrayType , ParameterizedType , TypeVariable , WildcardType 。
其中最常用的莫过于 Class,而对于其他几个子类则用的不多。
先说结论。
| 类型 | 举例 | 描述 |
|---|---|---|
| Class | String.class |
所有 class 的父类 |
| ParameterizedType | Class<T> |
带参数的类型 |
| TypeVariable | <T> |
泛型的参数 |
| WildcardType | <?> |
通配符类型 |
| GenericArrayType | T[] |
泛型数组 |
下面是测试代码:
public class TypeTest {
private <T> void func(Class<T> p0, Class<? super T> p1, Class<?> p2, T p3, T[] p4) {
}
@Test
public void testType() {
try {
Method func = TypeTest.class.getDeclaredMethod("func", Class.class, Class.class, Class.class, Object.class, Object[].class);
Type[] paramTypes = func.getGenericParameterTypes();
put("p0", paramTypes[0]);
put("p1", paramTypes[1]);
put("p2", paramTypes[2]);
put("p3", paramTypes[3]);
put("p4", paramTypes[4]);
System.out.println();
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void put(String tag, Type type) {
if (type == null) return;
System.out.println();
System.out.println();
System.out.print(String.format("%-12s -> ", tag));
System.out.print(String.format("%-28s -> ", type.getTypeName()));
if (type instanceof Class) {
System.out.print("Class ");
}
if (type instanceof TypeVariable) {
System.out.print("TypeVariable ");
}
if (type instanceof ParameterizedType) {
System.out.print("ParameterizedType ");
put(tag + ".rawType", ((ParameterizedType) type).getRawType());
put(tag + ".ownerType", ((ParameterizedType) type).getOwnerType());
put(tag + ".args[0]", ((ParameterizedType) type).getActualTypeArguments()[0]);
}
if (type instanceof WildcardType) {
System.out.print("WildcardType ");
}
if (type instanceof GenericArrayType) {
System.out.print("GenericArrayType ");
}
}
}
打印的结果为:
p0 -> java.lang.Class<T> -> ParameterizedType p0.rawType -> java.lang.Class -> Class p0.args[0] -> T -> TypeVariable p1 -> java.lang.Class<? super T> -> ParameterizedType p1.rawType -> java.lang.Class -> Class p1.args[0] -> ? super T -> WildcardType p2 -> java.lang.Class<?> -> ParameterizedType p2.rawType -> java.lang.Class -> Class p2.args[0] -> ? -> WildcardType p3 -> T -> TypeVariable p4 -> T[] -> GenericArrayType
为方便对照,这里再贴一下 func 方法的签名:
<T> void func(Class<T> p0, Class<? super T> p1, Class<?> p2, T p3, T[] p4);