import java.lang.reflect.AnnotatedType;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.stream.Stream;
public class GenericApi {
/**
* java.lang.reflect.Type: Type is the common superinterface for all types in the Java programming language.
* These include raw types, parameterized types, array types, type variables and primitive types.
* raw types:原始类型,String.class,java.util.AbstractList.class(没有带泛型)
* parameterized types:泛型参数类型,java.util.AbstractList<E>
* array types:数组类型
* type variables:泛型变量,Map<K,V>,K和V就是TypeVariable,如果
* primitive types: types:原生类型,包括基本数据类型
* <p>
* java.lang.Class#getGenericInfo():泛型信息
* java.lang.Class#getGenericSuperClass():如果类型有泛型信息,返回获取带有泛型参数的父类类型;如果类型没有泛型信息,返回父类类型
* java.lang.Class#getGenericInterface():泛型接口
*
* @param args
*/
public static void main(String[] args) {
// primitive types
Class intClass = int.class;
// array types
Class arrayClass = int[].class;
// raw types
Class stringClass = String.class;
ParameterizedType genericClass = (ParameterizedType) ArrayList.class.getGenericSuperclass();
// parameterized types
System.out.println(genericClass);
// raw types
System.out.println(genericClass.getRawType());
// type variables
Stream.of(genericClass.getActualTypeArguments()).forEach(v->{
TypeVariable v1 = (TypeVariable) v;
Type[] bounds = v1.getBounds();
GenericDeclaration genericDeclaration = v1.getGenericDeclaration();
AnnotatedType[] annotatedBounds = v1.getAnnotatedBounds();
System.out.println();
});
}
}
Java范型
最新推荐文章于 2024-05-10 09:34:03 发布