【问题标题】:No instance(s) of type variable(s) exist so that T conforms to Annotation不存在类型变量的实例,因此 T 符合 Annotation
【发布时间】:2019-12-16 01:43:40
【问题描述】:

我正在尝试编写一个通用函数来查找任何给定注释的值。在代码中,我没有在方法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";
}

【问题讨论】:

    标签: java java-8 annotations java-annotations


    【解决方案1】:

    您应该明确指出 &lt;T extends Annotation&gt; 以便它可以正常工作: 假设您有一个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 正如预期的那样

    【讨论】:

      猜你喜欢
      • 2017-04-22
      • 2020-07-13
      • 1970-01-01
      • 2022-10-18
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      相关资源
      最近更新 更多