所有类型注释都可以通过AnnotatedType层次结构检索,除了TypeVariable,它的注释可以通过AnnotatedTypeVariable.getType()检索,这将是TypeVariable的一个实例,它现在扩展了AnnotatedElement,碰巧与Method.getGenericReturnType()返回的对象一致。
因此您可以检索所有信息,例如
AnnotatedType art = myMethod.getAnnotatedReturnType();
System.out.print(
Arrays.toString(art.getAnnotations())+" "+art.getType().getTypeName()+" -> ");
final boolean typeVariable = art instanceof AnnotatedTypeVariable;
if (typeVariable) System.out.print('<');
System.out.print(Arrays.toString(((AnnotatedElement)art.getType()).getAnnotations()) + " ");
System.out.print(art.getType().getTypeName());
if (typeVariable) {
AnnotatedTypeVariable atv = (AnnotatedTypeVariable)art;
AnnotatedType[] annotatedBounds = atv.getAnnotatedBounds();
if (annotatedBounds.length > 0) {
System.out.print(" extends ");
for (AnnotatedType aBound: annotatedBounds) {
System.out.print(Arrays.toString(aBound.getAnnotations()) + " ");
System.out.print(aBound.getType().getTypeName() + ", ");
}
}
System.out.println(">");
}
将打印
[@A3()] S -> <[@A1()] S extends [@A2()] T, >
当您对((AnnotatedTypeVariable)myMethod.getAnnotatedReturnType()) .getAnnotatedBounds()[0].getAnnotations() 的调用未提供@A2 时,您应该重新检查A2 是否确实具有@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE_USE)。
当然,那是只处理您的特定方法的“简化”版本。
要处理所有可能的情况,您将需要更多的instanceofs,处理这些分离的类型层次结构Type 和AnnotatedType,尤其是在处理带注释的参数化类型和带注释的泛型数组类型时。
如前所述,TypeVariable 不同,因为它扩展了AnnotatedElement 并且还具有getAnnotatedBounds() 方法。因此,在这种特定情况下,处理该方法的另一种方法是
List<TypeVariable<?>> typeParameters = Arrays.asList(myMethod.getTypeParameters());
for (TypeVariable<?> tv: typeParameters) {
System.out.print("< "+Arrays.toString(tv.getAnnotations())+" "+tv.getName());
AnnotatedType[] annotatedBounds = tv.getAnnotatedBounds();
if (annotatedBounds.length > 0) {
System.out.print(" extends ");
for (AnnotatedType aBound: annotatedBounds) {
System.out.print(Arrays.toString(aBound.getAnnotations()) + " ");
System.out.print(aBound.getType().getTypeName() + ", ");
}
}
System.out.print("> ");
}
AnnotatedType art = myMethod.getAnnotatedReturnType();
System.out.print(Arrays.toString(art.getAnnotations()) + " ");
int ix = typeParameters.indexOf(art.getType());
if (ix >= 0) System.out.print("[ref to type parameter #" + ix + "] ");
System.out.println(art.getType().getTypeName());