Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

求助一个Java基础问题


????如上图,在使用自定义注解的过程中发现一个不太理解的现象,求大佬指教!getAnnotation方法返回一个A类型的结果,我在hh这个参数的引用明确指定了泛型为MyAnnotation,但是在后面调用getAnnotation时依旧需要强转,这让我非常困惑...另外我还发现使用Annotation引用去指向getAnnotation方法时不需要强转...

源代码下面附上

@MyAnnotation("heihei")
public class TestAnnotation {

    public void use(){
        Class clazz=TestAnnotation.class;
        Class<MyAnnotation> hh=MyAnnotation.class;
        
        try {
            Method method=clazz.getMethod("use");
            MyAnnotation an=(MyAnnotation) clazz.getAnnotation(hh);
            String vl=an.value();
            System.out.println(vl);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }


    }

    public static void main(String[] args) {
        TestAnnotation t= new TestAnnotation();
        t.use();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

泛型的生效在于编译期,java代码运行时会对泛型进行擦除,所以前面指定的泛型类型并没有意义,仍需进行类型强转


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...