开发者

Why can't I use a getAnnotation() on a reference of Annotation?

开发者 https://www.devze.com 2023-03-13 20:41 出处:网络
We can use getAnnotations() on an interface of Annotation but not getAnnotation? Why When I changed the interface from MyAnno to Annotation in the followng program, the compiler was not recognizing th

We can use getAnnotations() on an interface of Annotation but not getAnnotation? Why When I changed the interface from MyAnno to Annotation in the followng program, the compiler was not recognizing the data defined in the Annotation like the str() etc...

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.开发者_StackOverflowclass);
    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();

}

}


As far as I understand, you want to change this line

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

to

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

Of course, now anno is of type java.lang.annotation.Annotation and that interface does not define your methods str(), yuiop() and fdfd(). That's why the compiler complains in the following line.

Like with ordinary java types, you'll have to cast back to the real annotation:

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


Your program seems to be working correctly. I get the following output when i run it...

run-single:
Annotation Example 100 4.267
BUILD SUCCESSFUL (total time: 12 seconds)

I'm i missing something in your question?

I also changed the code to use the getAnnotations() method and recieved the same result...

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());
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号