【发布时间】:2016-06-14 16:11:26
【问题描述】:
我正在编写一些简单的方法来获取类、字段或方法的注释。第一个方法,它得到一个类级别的注释,工作正常。复制并粘贴它以创建获取字段级注释的新方法会导致编译错误:
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);
}
}
}
【问题讨论】:
标签: java class generics annotations field