java - 为什么 null 被禁止作为注释中的默认值?

标签 java null annotations default-value

根据 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 value V if and only if one of the following is true:

  • T is an array type E[], and either:
    • If V is a ConditionalExpression or an Annotation, then V is commensurate with E; or

    • If V is an ElementValueArrayInitializer, then each element value that V contains is commensurate with E.

      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 of V is assignment compatible (§5.2) with T, and:
    • If T is a primitive type or String, then V is a constant expression (§15.29).
    • If T is Class or an invocation of Class (§4.5), then V is a class literal (§15.8.2).
    • If T is an enum type (§8.9), then V is an enum constant (§8.9.1).
    • V is not null.

禁止 null 的最后一个项目符号可能看起来很武断,但即使没有那个项目符号,null 也不是合法值,因为它既不是常量表达式,也不是类文字,也不是枚举常量。

所以最后一个项目符号只是明确表示这不是疏忽。

当注释被添加到语言中时,编译时常量的定义就已经存在,包括用于存储它们的字节码格式。类文字也在句法上定义,尽管与常量不相上下。但是用 JDK-4662563 ,它们的字节码格式变得等同于同一版本中的其他常量。因此,对类文字的支持对于注释来说也是自然的。

唯一为注释支持添加的独特功能是对枚举常量的引用和数组的存储格式。两者都立即证明了它们的用处,因为注释定义本身所需的内置注释 @RetentionTarget 都使用枚举常量,而后者也使用数组。

因此,null 并未从合法构造集中移除,它从未被添加。包含所考虑的用例既不是​​直接的或自然的,也不是立即需要的。

This answer表明添加对 null 的支持的建议最初已被考虑用于类型注释提案(另请参阅 the archive link ),此时反对意见被命名为 right 。众所周知,类型注释是在 Java 8 中引入的,对 null 的支持不是(其他建议,如可重复注释,已纳入语言)。

关于java - 为什么 null 被禁止作为注释中的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54659831/

相关文章:

java - 从文本文件中读取并解析为ArrayList

java - 将现有项目转换为maven项目

mysql - MySQL的DEFAULT NULL和CHECKBOX NULL有什么区别?

android - Kotlin 对 @ColorInt Java 注释的支持

ios - 如何在 iPhone 中使用图像和标签在 Mapview 中添加注释?

java - 分隔 arraylist 的元素

java - 在 Spoon (Pentaho Kettle) 中执行 .jar 文件

c# - linq sql查找重复项但将null和空字符串视为相同

c# - 了解 C# 泛型和 Nullable 值类型。返回 null 或 nullable

android - Android注解中Main Thread、Ui Thread、WorkerThread、Binder Thread的区别