找不到适合 getAnnotation(Class<CAP#1>) 的方法
no suitable method found for getAnnotation(Class<CAP#1>)
我正在编写一些简单的方法来获取 class、字段或方法的注释。第一种方法,获得 class 级别的注释,工作正常。复制并粘贴它以创建一个新方法来获取字段级注释导致编译错误:
error: no suitable method found for getAnnotation(Class<CAP#1>)
不确定 Class 对象上的 getAnnotation 方法调用如何正常工作,但 Field 对象上的相同方法调用会导致此编译错误。
想法?
public class AnnotationTool {
public static <T> T getAnnotation(Class c, Class<? extends T> annotation) {
return (T)c.getAnnotation(annotation);
}
public static <T> T getAnnotation(Class c, String fieldName, Class<? extends T> annotation) {
try {
Field f = c.getDeclaredField(fieldName);
return (T)f.getAnnotation(annotation); // compile error here??
} catch (NoSuchFieldException nsfe) {
throw new RuntimeException(nsfe);
}
}
}
Field.getAnnotation
期望 class 是注释的子 class:
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
因此在您的辅助方法中,您需要相应地限制您的类型参数:
public static <T extends Annotation> T getAnnotation(Class<?> c, String fieldName, Class<T> annotation) {
请注意,这同样适用于您的 class 级别辅助方法。但是您使用了原始类型 Class c
阻止了编译器发出相同的错误。
我正在编写一些简单的方法来获取 class、字段或方法的注释。第一种方法,获得 class 级别的注释,工作正常。复制并粘贴它以创建一个新方法来获取字段级注释导致编译错误:
error: no suitable method found for getAnnotation(Class<CAP#1>)
不确定 Class 对象上的 getAnnotation 方法调用如何正常工作,但 Field 对象上的相同方法调用会导致此编译错误。
想法?
public class AnnotationTool {
public static <T> T getAnnotation(Class c, Class<? extends T> annotation) {
return (T)c.getAnnotation(annotation);
}
public static <T> T getAnnotation(Class c, String fieldName, Class<? extends T> annotation) {
try {
Field f = c.getDeclaredField(fieldName);
return (T)f.getAnnotation(annotation); // compile error here??
} catch (NoSuchFieldException nsfe) {
throw new RuntimeException(nsfe);
}
}
}
Field.getAnnotation
期望 class 是注释的子 class:
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
因此在您的辅助方法中,您需要相应地限制您的类型参数:
public static <T extends Annotation> T getAnnotation(Class<?> c, String fieldName, Class<T> annotation) {
请注意,这同样适用于您的 class 级别辅助方法。但是您使用了原始类型 Class c
阻止了编译器发出相同的错误。