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

标签 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;
}

最佳答案

Class is not commensurate with the value Integer.TYPE

It is a compile-time error if the element type is not commensurate with the element value. An element type T is commensurate with an element value V if and only if one of the following is true:

  • [...]

  • If T is Class or an invocation of Class (§4.5), then V is a class literal (§15.8.2).

来自Integer的源代码

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

表达式Integer#TYPE不是类文字。如果您想要的话,Integer.classint.class 都可以。

关于java - 为什么 "Integer.TYPE"在注释 "attribute value must be constant"中显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36563235/

相关文章:

java - 如何保持鼠标相对于屏幕的位置并忽略组件旋转?

java - 哈希表/插入新键和值

Java:如何描述一个网络数据包?

java - Jackson JsonView 和 JsonTypeInfo

java - 可重复注释目标子集不匹配编译器错误

java - 有没有办法在特定类的子类中强制使用特定的 Java 注释

java - Java 会自动缓存注释和类元数据吗?

java - Hadoop 中的Reducer 在集群上运行时出现异常

java - 错误 : "attribute value must be constant". 我可以在编译时从枚举构造常量吗?

java - 如何使用 xtend 设置 java 注释的多个属性(使用 xbase)