【问题标题】:no suitable method found for getAnnotation(Class<CAP#1>)没有找到适合 getAnnotation(Class<CAP#1>) 的方法
【发布时间】: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


    【解决方案1】:

    Field.getAnnotation 需要一个作为注解子类的类:

    public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
    

    因此,在您的辅助方法中,您需要相应地限制您的类型参数:

    public static <T extends Annotation> T getAnnotation(Class<?> c, String fieldName, Class<T> annotation) {
    

    请注意,您的类级别辅助方法也是如此。但是您使用了原始类型 Class c,它阻止了编译器发出相同的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      • 2014-08-27
      • 2021-06-19
      • 2015-11-26
      • 2019-09-26
      • 1970-01-01
      相关资源
      最近更新 更多