我们可以在Annotation的接口上使用getAnnotations()而不是getAnnotation吗?为什么 当我在followng程序中将接口从MyAnno更改为Annotation时,编译器没有像str()等那样识别Annotation中定义的数据......
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();
}
}
答案 0 :(得分:1)
据我了解,您想要更改此行
Hashingsnr anno = m.getAnnotation(Hashingsnr.class);
到
Annotation 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());
答案 1 :(得分:0)
您的程序似乎正常运行。当我运行它时,我得到以下输出...
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());
}
}