Java 反射之 TypeVariable

TypeVariable是类型变量(泛型变量),在Java 反射之 GenericDeclaration中提到,Java中可以声明泛型变量的地方有三个class,contructor和method,TypeVariable接口的声明如下:

public interface TypeVariable extends Type, AnnotatedElement {
    Type[] getBounds();  
    D getGenericDeclaration();
    String getName();
    AnnotatedType[] getAnnotatedBounds();
}
  1. getBounds是拿获取类型变量的边界
  2. getGenericDeclaration是获取到声明类型变量的语法元素,哪个class,哪个class的哪个构造方法,哪个class的哪个方法;

下面以在class上的TypeVariable为例,在contructor和method上是一样的;

public class TypeVariableSample") Comparable> {

}
public static void main(String[] args) {
		TypeVariable>[] typeParameters = TypeVariableSample.class.getTypeParameters();

		for (int i = 0; i < typeParameters.length; i++) {
			TypeVariable> typeVariable = typeParameters[i];
			System.out.println(typeVariable.getName());
			System.out.println(typeVariable.getGenericDeclaration());

			Type[] bounds = typeVariable.getBounds();
			for (int j = 0; j < bounds.length; j++) {
				Type bound = bounds[j];
				System.out.println(bound.getTypeName());
			}
			AnnotatedType[] annotatedBounds = typeVariable.getAnnotatedBounds();
			for (int j = 0; j < annotatedBounds.length; j++) {
				StringBuilder sb = new StringBuilder();
				AnnotatedType annotatedType = annotatedBounds[j];
				System.out.println("AnnotatedType:" + annotatedType.getType());
				Annotation[] annotations = annotatedType.getDeclaredAnnotations();
				for (int k = 0; k < annotations.length; k++) {
					Annotation annotation = annotations[k];
					sb.append(annotation);
				}
				sb.append(" "+ annotatedType.getType().getTypeName());
				System.out.println(sb.toString());
			}
		}
	}

你可能感兴趣的:(Java)