gpt4 book ai didi

java - 为什么我不能对 Annotation 的引用使用 getAnnotation()?

转载 作者:行者123 更新时间:2023-12-01 15:49:35 25 4
gpt4 key购买 nike

我们可以在 Annotation 的接口(interface)上使用 getAnnotations() 但不能在 getAnnotation 上使用?为什么当我在以下程序中将接口(interface)从 MyAnno 更改为 Annotation 时,编译器无法识别 Annotation 中定义的数据,如 str() 等......

package british_by_blood;

import java.lang.annotation.*;
import java.lang.reflect.*;

@Retention (RetentionPolicy.RUNTIME)
@interface Hashingsnr {
String str();
int yuiop();
double fdfd();
}


public class German_by_Descent {
@Hashingsnr(str = "Annotation Example", yuiop = 100, fdfd = 4.267)
public void mymeth(){
German_by_Descent ob = new German_by_Descent();
try{
Class c = ob.getClass();
Method m = c.getMethod("mymeth");
Hashingsnr anno = m.getAnnotation(Hashingsnr.class);
System.out.println(anno.str() + " " + anno.yuiop() + " " + anno.fdfd());

}catch(NoSuchMethodException exc){
System.out.println("Method Not Found");
}
}
public static void main(String[] args) {

German_by_Descent ogb = new German_by_Descent();

ogb.mymeth();

}

}

最佳答案

据我了解,您想更改此行

Hashingsnr anno = m.getAnnotation(Hashingsnr.class);

Annotation anno = m.getAnnotation(Hashingsnr.class);

当然,现在 annojava.lang.annotation.Annotation 类型,并且该接口(interface)没有定义您的方法 str()yuiop()fdfd()。这就是编译器在下面一行中提示的原因。

与普通的 java 类型一样,您必须转换回真正的注释:

System.out.println(
((Hashingsnr) anno).str() + " " +
((Hashingsnr) anno).yuiop() + " " +
((Hashingsnr) anno).fdfd());

关于java - 为什么我不能对 Annotation 的引用使用 getAnnotation()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6385069/

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