简体   繁体   中英

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

I am trying to write a generic function to find value of any given annotation. In code, instead of directly using abc.class (as a parameter) in method getAnnotation , I am using variable of type Class<T> . While doing so, following error is being generated:

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

I believe, the error says that the compiler won't be able to know whether this generic class is of type Annotation or not.

Any ideas on how to resolve this issue ?

Sample Code:

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";
}

You should make explicit that <T extends Annotation> so it can work properly: Let's say you have an Annotation @interface :


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

and the following class with an annotated Field

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

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

So now if you have a function like:

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);
    }
}

When you execute:

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

It will output:

An ObjA attribute as expected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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