【问题标题】:Why does "Integer.TYPE" show error in annotation "attribute value must be constant"为什么“Integer.TYPE”在注释“属性值必须是常量”中显示错误
【发布时间】:2016-04-12 03:42:21
【问题描述】:

我创建了一个注释:

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

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

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

【问题讨论】:

    标签: java annotations java-annotations


    【解决方案1】:

    Class is not commensurate with the value Integer.TYPE

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

    • [...]

    • 如果TClassClass 的调用(第4.5 节),那么V 是一个类 文字(第 15.8.2 节)。

    来自Integer的源码

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

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

    【讨论】:

      【解决方案2】:

      尝试使用int.class 而不是Integer.TYPE

      @Test(int.class)
      

      【讨论】:

        猜你喜欢
        • 2013-04-05
        • 1970-01-01
        • 1970-01-01
        • 2012-12-22
        • 1970-01-01
        • 1970-01-01
        • 2015-03-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多