不存在类型变量的实例,因此T符合注释

时间:2019-08-08 10:59:03

标签: java java-8 annotations java-annotations

我正在尝试编写一个通用函数来查找任何给定注释的值。在代码中,我不是在方法abc.class中直接使用getAnnotation(作为参数),而是使用类型为Class<T>的变量。 这样做时,正在生成以下错误:

getAnnotation(java.lang.Class<T>) in Field cannot be applied
to           (java.lang.Class<T>)

reason: No instance(s) of type variable(s) exist so that T conforms to Annotation

我相信,该错误表明编译器将无法知道此泛型类是否为Annotation类型。

关于如何解决此问题的任何想法?

示例代码:

private static <T> String f1(Field field, Class<T> clas){

    // Following Gives Error: No instance(s) of type variable(s) exist so that T conforms to Annotation
    String val =  field.getAnnotation(clas).value();

    //Following works fine
    val =  field.getAnnotation(Ann1.class).value();
    val =  field.getAnnotation(Ann2.class).value();

    return val;
}

// *************** Annotations ***********

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Ann1 {
    public String value() default "DEFAULT1";
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Ann2 {
    public String value() default "DEFAULT2";
}

1 个答案:

答案 0 :(得分:0)

您应该明确说明<T extends Annotation>,以便它可以正常工作: 假设您有一个Annotation @interface


@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface YouAre{
    String denomination() default "Unknown";
} 

以及带有注释的Field

的以下类
class ObjA {
    @YouAre(denomination = "An ObjA attribute")
    private String description;

    public ObjA(String description) {
        this.description = description;
    }
    //...Getter, toString, etc...
}

现在,如果您具有类似以下功能:

class AnnotationExtractor {
    public static final AnnotationExtractor EXTRACTOR = new AnnotationExtractor();

    private AnnotationExtractor() {

    }

    public <T extends Annotation> T get(Field field, Class<T> clazz) {
        return field.getAnnotation(clazz);
    }
}

执行时:

  Field objAField = ObjA.class.getDeclaredField("description");
  YouAre ann = EXTRACTOR.get(objAField, YouAre.class);
  System.out.println(ann.denomination());

它将输出:

An ObjA attribute 符合预期