为什么“Integer.TYPE”在注释中显示错误“属性值必须是常量”

时间:2016-04-12 03:42:22

标签: java annotations java-annotations

我创建了一个注释:

@Target(ElementType.FIELD )
@Retention( RetentionPolicy.RUNTIME )
public @interface Test
{
    Class something();
}

但是当我用Integer.TYPE调用它时(对于int的返回类型),它会显示错误。

public class TestA
{
    @Test(Integer.TYPE)
    public int id;
}

2 个答案:

答案 0 :(得分:1)

Class is not commensurate with the value Integer.TYPE

  

如果元素类型不相称,则为编译时错误   与元素值。元素类型T与a相称   元素值V当且仅当满足下列条件之一时:

     
      
  • [...]

  •   
  • 如果TClass或调用Class(§4.5),则V为班级   字面意思(§15.8.2)。

  •   

来自Integer

的源代码
public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");

表达式Integer#TYPE不是类文字。 Integer.classint.class会起作用,如果这就是您所追求的目标。

答案 1 :(得分:1)

尝试使用int.class代替Integer.TYPE

@Test(int.class)
相关问题