我正在尝试编写一个通用函数来查找任何给定注释的值。在代码中,而不是直接使用 abc.class
(作为参数)在方法 getAnnotation
中,我正在使用 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
正如预期的那样
关于java - 不存在类型变量的实例,因此 T 符合注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57411022/