java.lang.Class
public native Class<?> getComponentType()
返回表示数组组件类型的 Class
System.out.println(String.class.getComponentType()); 返回null
System.out.println(String[].class.getComponentType()); 返回java.lang.String
System.out.println(String[][].class.getComponentType()); 返回[Ljava.lang.String;
java.lang.reflect.GenericArrayType
Type getGenericComponentType();
返回表示泛型数组组件类型的Type
public class Test {
public static void main(String[] args) throws NoSuchMethodException {
Class testClass = Test.class;
Method method = testClass.getMethod("test", ArrayList[][].class);
Type[] types = method.getGenericParameterTypes();
for (Type type : types) {
if (type instanceof GenericArrayType) {
System.out.println("GenericArrayType1 : " + type.toString());
GenericArrayType genericArrayType = (GenericArrayType) type;
Type getype = genericArrayType.getGenericComponentType();
System.out.println("GenericArrayType2 : " + getype.toString());
if (getype instanceof GenericArrayType) {
GenericArrayType genericArrayType2 = (GenericArrayType) getype;
Type getype2 = genericArrayType2.getGenericComponentType();
System.out.println(getype2.toString());
if (getype2 instanceof Class) {
System.out.println("Class");
} else if (getype2 instanceof ParameterizedType) {
System.out.println("ParameterizedType");
} else if (getype2 instanceof GenericArrayType) {
System.out.println("GenericArrayType3");
}
}
} else if (type instanceof ParameterizedType) {
System.out.println("ParameterizedType");
} else if (type instanceof Class) {
System.out.println("class");
}
}
}
public static void test(ArrayList<String>[][] as) {
}
}
输出结果:
GenericArrayType1 : java.util.ArrayList<java.lang.String>[][]
GenericArrayType2 : java.util.ArrayList<java.lang.String>[]
java.util.ArrayList<java.lang.String>
ParameterizedType
将test方法的参数类型改为ArrayList[][] 输出结果为:
class
总结:这两个方法用来一级一级脱去数组的维数,getComponentType用来处理普通类型数组
getGenericComponentType用来处理泛型数组