簡體   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