这是Lombok的NonNull
注释的java-doc:
If put on a parameter, lombok will insert a null-check at the start of the method / constructor's body, throwing a {@code NullPointerException} with the parameter's name as message. If put on a field, any generated method assigning a value to this field will also produce these nullchecks. Note that any annotation named {@code NonNull} with any casing and any package will result in nullchecks produced for generated methods (and the annotation will be copied to the getter return type and any parameters of generated methods), but only this annotation, if present on a parameter, will result in a null check inserted into your otherwise handwritten method.
WARNING: If the java community ever does decide on supporting a single {@code @NonNull} annotation (for example via JSR305), then this annotation will be deleted from the lombok package. If the need to update an import statement scares you, you should use your own annotation named {@code @NonNull} instead of this one.
拥有自己的注释的最简单方法是什么,比如说NonNull
Nonnull
,Lombok根据我的注释注入(inject)空检查注释?
更新:我的问题很热衷于为方法参数使用注释。
最佳答案
首先,您需要将其命名为nonNull
(大小写无关)。 Lombok 不会识别 NotNull
。此外,您还需要设置另一个 Lombok 注释(例如 @Data
、@Setter
...),以便 Lombok 处理您的类型。
总结您的自定义注释可能不如 @lombok.NonNull
注释本身有值(value)。当您的类型不包含任何其他 Lombok 注释时,您可以从 @lombok.NonNull
注释中受益,甚至不会处理您的自定义注释,例如:
class NoLombokAnnotationsAnywhere {
void testMe(@lombok.NonNull String nonNull) { /* .. */ }
}
一旦调用new NoLombokAnnotationsAnywhere().testMe(null)
,就会产生NullPointerException
。而这不会与您的自定义注释一起抛出任何内容。当然,这只适用于没有任何其他 Lombok 注释的情况。一旦 Lombok 处理该类型,您的注释也会得到处理。
如果您有自己的 NonNull
注释,那么您可以添加另一个看起来合适的 Lombok 注释,Lombok 会为您添加空检查,例如:
@Data
class NonNullData {
@mycustom.Nonnull
String value;
}
// Calling the following throws a NullPointerException as expected
new NonNullData(null);
您可能还会发现以下相关问题:Support annotations named @NotNull as well as @NonNull
关于java - Lombok 中的自定义 `NonNull` 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43295026/