【发布时间】: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