天天看點

Java 反射之 TypeVariable

public interface TypeVariable<D extends GenericDeclaration> extends Type, AnnotatedElement {
    Type[] getBounds();  
    D getGenericDeclaration();
    String getName();
    AnnotatedType[] getAnnotatedBounds();
}      
  1. getBounds是拿擷取類型變量的邊界
  2. getGenericDeclaration是擷取到聲明類型變量的文法元素,哪個class,哪個class的哪個構造方法,哪個class的哪個方法;
public class TypeVariableSample<T extends @Location("Serializable") Serializable & @Location("Comparable<T>") Comparable<T>> {

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

    for (int i = 0; i < typeParameters.length; i++) {
      TypeVariable<Class<TypeVariableSample>> 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());
      }
    }
  }