根据 Annotation default "null" value , null 值被禁止作为注释中的默认值。 我想知道为什么。这是什么原因?
最佳答案
请注意,null
不仅不支持作为默认值,而且通常也不支持作为注释值。
JLS §9.7.1指定:
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 valueV
if and only if one of the following is true:
T
is an array typeE[]
, and either:
If
V
is a ConditionalExpression or an Annotation, thenV
is commensurate withE
; orIf
V
is an ElementValueArrayInitializer, then each element value thatV
contains is commensurate withE
.An ElementValueArrayInitializer is similar to a normal array initializer (§10.6), except that an ElementValueArrayInitializer may syntactically contain annotations as well as expressions and nested initializers. However, nested initializers are not semantically legal in an ElementValueArrayInitializer because they are never commensurate with array-typed elements in annotation type declarations (nested array types not permitted).
T
is not an array type, and the type ofV
is assignment compatible (§5.2) withT
, and:
禁止 null
的最后一个项目符号可能看起来很武断,但即使没有那个项目符号,null
也不是合法值,因为它既不是常量表达式,也不是类文字,也不是枚举常量。
所以最后一个项目符号只是明确表示这不是疏忽。
当注释被添加到语言中时,编译时常量的定义就已经存在,包括用于存储它们的字节码格式。类文字也在句法上定义,尽管与常量不相上下。但是用 JDK-4662563 ,它们的字节码格式变得等同于同一版本中的其他常量。因此,对类文字的支持对于注释来说也是自然的。
唯一为注释支持添加的独特功能是对枚举常量的引用和数组的存储格式。两者都立即证明了它们的用处,因为注释定义本身所需的内置注释 @Retention
和 Target
都使用枚举常量,而后者也使用数组。
因此,null
并未从合法构造集中移除,它从未被添加。包含所考虑的用例既不是直接的或自然的,也不是立即需要的。
This answer表明添加对 null
的支持的建议最初已被考虑用于类型注释提案(另请参阅 the archive link ),此时反对意见被命名为 right 。众所周知,类型注释是在 Java 8 中引入的,对 null
的支持不是(其他建议,如可重复注释,已纳入语言)。
关于java - 为什么 null 被禁止作为注释中的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54659831/