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