@NotNull 和@Nullable,与 java 注释相矛盾

@NotNull and @Nullable, contradicting java annotations

发生在我​​身上,我不小心做了这个:

@javax.annotation.Nullable
@javax.validation.constraints.NotNull

编译器没有报错,一切似乎都运行良好。

现在我想知道当两个或多个注释相互矛盾时内部发生了什么。此外,顺序重要吗?

这是

@Nullable
@NotNull

和这个一样吗?

@NotNull
@Nullable

一般来说,这对注释有何作用?谁赢了?

编辑:我正在寻找一个一般性的答案,不一定是关于这两个注释的

注释不会改变程序的含义。 Java 编译器将它们添加到程序的内部表示中(仅在编译期间,或保存在 class 文件中,甚至在 运行 时),但它会忽略它们。特别是,它不知道 "conflicting" 注释。

注释由外部工具或库使用,它们可以以任何他们想要的方式处理冲突的注释(例如,通过打印错误消息)。

注释本身不会给您的代码带来任何逻辑。每个注释都应该使用适当的注释处理器进行处理。注释处理器是使注释有意义的人。

勾选 official tutorial:

Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

Annotations have a number of uses, among them:

  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
  • Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
  • Runtime processing — Some annotations are available to be examined at runtime.

让我们考虑一下您上面提到的这 2 个特定注释。首先,它们不是相互排斥的,具有不同的性质。

@javax.annotation.NullableJSR-305 and it has the opposite one - @javax.annotation.Nonnull. These annotations are designed to annotate your class fields, method params and method results. You can use them with code analyzers, one of them is Findbugs

的一部分

@javax.validation.constraints.NotNullJSR-303 aka Bean Validation 的一部分。所以这个注释与 @javax.annotation.Nullable 没有任何共同点,因为这些注释有不同的处理器。

每次你对注解语义有任何疑问时,你应该检查文档,当然你可以运行你写代码看看会发生什么。