gpt4 book ai didi

java - 没有找到适合 getAnnotation(Class) 的方法

转载 作者:行者123 更新时间:2023-12-02 03:33:00 24 4
gpt4 key购买 nike

我正在编写一些简单的方法来获取类、字段或方法的注释。第一种方法获得类级注释,效果很好。复制并粘贴该内容以创建一个新方法来获取字段级注释,结果会出现编译错误:

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 需要一个作为注释子类的类:

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,这阻止了编译器发出相同的错误。

关于java - 没有找到适合 getAnnotation(Class<CAP#1>) 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37817177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com