为什么"Integer.TYPE"在注释"attribute value must be constant"中显示错误



我创建了一个注释:

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

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

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

Class与值Integer.TYPE 不相称

如果元素类型不相称,则是编译时错误具有元素值。元素类型T与元素值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会起作用,如果这就是你想要的。

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

@Test(int.class)

相关内容

最新更新