Java 为什么可以';我对注释的引用使用getAnnotation()吗?
我们可以在Annotation的接口上使用getAnnotations(),但不能在getAnnotation上使用?为什么? 当我在下面的程序中将接口从MyAnno更改为Annotation时,编译器无法识别在Annotation中定义的数据,如str()等Java 为什么可以';我对注释的引用使用getAnnotation()吗?,java,Java,我们可以在Annotation的接口上使用getAnnotations(),但不能在getAnnotation上使用?为什么? 当我在下面的程序中将接口从MyAnno更改为Annotation时,编译器无法识别在Annotation中定义的数据,如str()等 您的程序似乎工作正常。当我运行它时,我得到以下输出 run-single: Annotation Example 100 4.267 BUILD SUCCESSFUL (total time: 12 seconds) 我在你的问题中遗漏
您的程序似乎工作正常。当我运行它时,我得到以下输出
run-single:
Annotation Example 100 4.267
BUILD SUCCESSFUL (total time: 12 seconds)
我在你的问题中遗漏了什么
我还将代码更改为使用getAnnotations()方法,并收到了相同的结果
final Annotation[] annos = m.getAnnotations();
for (Annotation anno : annos) {
if (anno instanceof Hashingsnr) {
final Hashingsnr impl = (Hashingsnr)anno;
System.out.println(impl.str() + " " + impl.yuiop() + " " + impl.fdfd());
}
}
据我所知,你想改变这一行
Hashingsnr anno = m.getAnnotation(Hashingsnr.class);
到
当然,现在anno
属于java.lang.annotation.annotation
类型,并且该接口不定义方法str()
、yuiop()
和fdfd()
。这就是编译器在下一行中抱怨的原因
与普通java类型一样,您必须回溯到真正的注释:
System.out.println(
((Hashingsnr) anno).str() + " " +
((Hashingsnr) anno).yuiop() + " " +
((Hashingsnr) anno).fdfd());
我得到以下输出:
注释示例100 4.267
-看起来不错。在本例中,您没有MyAnno
注释,请编辑您的问题,以澄清您的实际更改是什么?对不起,这是Hashingsnr。。。。每当我在第26行(首先)将其更改为注释,然后在第27行str、yuiop和fdfd加下划线,给出找不到符号的错误。真的很抱歉,伙计们,请参见第2条注释为什么我们可以将getAnnotations与注释一起使用?then@AbhaySaini-Annotation
没有定义getAnnotations
方法-所以如果我没弄错的话,就不定义了@阿比,你可以。但您也不会看到这些方法。您能否使用注释
reference在调用Hashingsnr
中定义的方法的地方发布代码?。可能您正在导入自定义的注释
或其他内容。@Abhay Saini-所有注释都扩展了接口注释
。是的。我想迈克尔·J·李给出了一个正确的答案,但我不明白。。请你解释一下。它使用继承,因为getAnnotations()可以返回多种类型的注释。如果要使用getAnnotations(),必须使用'instanceof'关键字检查它是否为HashingNR。检查我使用getAnnotations的第二个代码段,然后检查它是否是instanceof我只是想问为什么我们可以将getAnnotations与Annotation一起使用,而不使用getAnnotation?它使用继承,因为getAnnotations()可以返回多种类型的注释。如果要使用getAnnotations(),必须使用'instanceof'关键字检查它是否为HashingNR。检查我使用getAnnotations的第二个代码段,然后检查它是否是instanceof。
Annotation anno = m.getAnnotation(Hashingsnr.class);
System.out.println(
((Hashingsnr) anno).str() + " " +
((Hashingsnr) anno).yuiop() + " " +
((Hashingsnr) anno).fdfd());