ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java-注释“不兼容类型”编译器错误

2019-11-01 12:13:13  阅读:240  来源: 互联网

标签:annotations java


出于好奇:我关注了SSCCE

import javax.ws.rs.Path;

    @Path("/")
       public class T {

        void a() {

            Path p = getClass().getAnnotation(Path.class); //1

            Class z = getClass();
            p = z.getAnnotation(Path.class); //2
        }
}

编译器给出以下错误信息:

T.java:12: incompatible types
found   : java.lang.annotation.Annotation
required: javax.ws.rs.Path
        p = z.getAnnotation(Path.class); 
Note: T.java uses unchecked or unsafe operations.

// 1和// 2行的区别是什么?

解决方法:

这是原始类型的奇怪特征.当您使用通用类型(Class T)作为原始类型(Class)时,其成员将被视为其擦除.

JLS §4.8 Raw Types

The type of a constructor (§8.8), instance method (§8.8, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the erasure of its type in the generic declaration corresponding to C.

实际上,使用原始类型会在其成员的声明中禁用所有与泛型相关的东西.

在您的情况下,Class< T>的方法是声明为

public <A extends Annotation> A getAnnotation(Class<A> annotationClass) 

变成擦除

public Annotation getAnnotation(Class annotationClass) 

并由于将注释分配给路径而导致错误.

为了防止这种情况,您需要以参数化形式使用泛型.如果您不关心Class< T>中T的实际值,请使用通配符:

void b(Class<?> z) {
    Path p = z.getAnnotation(Path.class); 
}   

标签:annotations,java
来源: https://codeday.me/bug/20191101/1983633.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有