繁体   English   中英

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

[英]No instance(s) of type variable(s) exist so that T conforms to Annotation

我正在尝试编写一个通用函数来查找任何给定注释的值。 在代码中,我不是在方法getAnnotation中直接使用abc.class (作为参数),而是在使用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";
}

您应该明确表示<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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM