我希望使我的代码更具可读性,以及使用工具,如IDE代码检查和/或静态代码分析(FindBugs和Sonar),以避免nullpointerexception。许多工具似乎与彼此的@NotNull/@NonNull/ @NonNull注释不兼容,在我的代码中列出所有这些工具会让人难以阅读。有没有什么建议,哪一个是“最好的”?下面是我找到的等价注释列表:
javax.validation.constraints.NotNull
Created for runtime validation, not static analysis.
documentation
edu.umd.cs.findbugs.annotations.NonNull
Used by FindBugs (dead project) and its successor SpotBugs static analysis and therefore Sonar (now Sonarqube)
FindBugs documentation, SpotBugs documentation
javax.annotation.Nonnull
This might work with FindBugs too, but JSR-305 is inactive. (See also: What is the status of JSR 305?)
source
org.jetbrains.annotations.NotNull
Used by IntelliJ IDEA IDE for static analysis.
documentation
lombok.NonNull
Used to control code generation in Project Lombok.
Placeholder annotation since there is no standard.
source,
documentation
androidx.annotation.NonNull
Marker annotation available in Android, provided by annotation package
documentation
org.eclipse.jdt.annotation.NonNull
Used by Eclipse for static code analysis
documentation
如果你正在使用Spring框架构建应用程序,我建议使用来自bean Validation的javax.validation.constraints.NotNull,它被打包在以下依赖项中:
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
这种注释的主要优点是Spring同时支持用javax.validation.constraints.NotNull注释的方法参数和类字段。要启用支持,您需要做的是:
supply the api jar for beans validation and jar with implementation of validator of jsr-303/jsr-349 annotations (which comes with Hibernate Validator 5.x dependency):
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
provide MethodValidationPostProcessor to spring's context
@Configuration
@ValidationConfig
public class ValidationConfig implements MyService {
@Bean
public MethodValidationPostProcessor providePostProcessor() {
return new MethodValidationPostProcessor()
}
}
finally you annotate your classes with Spring's org.springframework.validation.annotation.Validated and validation will be automatically handled by Spring.
例子:
@Service
@Validated
public class MyServiceImpl implements MyService {
@Override
public Something doSomething(@NotNull String myParameter) {
// No need to do something like assert myParameter != null
}
}
当您尝试调用方法doSomething并传递null作为参数值时,spring(通过HibernateValidator)将抛出ConstraintViolationException。这里不需要手工工作。
您还可以验证返回值。
javax.validation.constraints.NotNull对Beans验证框架的另一个重要好处是,目前它仍在开发中,新特性计划在新版本2.0中实现。
@Nullable呢?在Beans Validation 1.1中没有类似的东西。好吧,我可以争辩说,如果你决定使用@ nonull,而不是任何没有用@NonNull注释的东西都是有效的“nullable”,所以@Nullable注释是无用的。
我非常喜欢检查器框架,它是类型注释(JSR-308)的实现,用于实现像null检查器这样的缺陷检查器。我并没有尝试其他任何方法进行比较,但我对这个实现感到满意。
我没有加入提供该软件的组织,但我是它的粉丝。
我喜欢这个系统的四个方面:
It has a defect checkers for nullness (@Nullable), but also has ones for immutability and interning (and others). I use the first one (nullness) and I'm trying to get into using the second one (immutability/IGJ). I'm trying out the third one, but I'm not certain about using it long term yet. I'm not convinced of the general usefulness of the other checkers yet, but its nice to know that the framework itself is a system for implementing a variety of additional annotations and checkers.
The default setting for nullness checking works well: Non-null except locals (NNEL). Basically this means that by default the checker treats everyhing (instance variables, method parameters, generic types, etc) except local variables as if they have a @NonNull type by default. Per the documentation:
The NNEL default leads to the smallest number of explicit annotations in your code.
You can set a different default for a class or for a method if NNEL doesn't work for you.
This framework allows you to use with without creating a dependency on the framework by enclosing your annotations in a comment: e.g. /*@Nullable*/. This is nice because you can annotate and check a library or shared code, but still be able to use that library/shared coded in another project that doesn't use the framework. This is a nice feature. I've grown accustom to using it, even though I tend to enable the Checker Framework on all my projects now.
The framework has a way to annotate APIs you use that aren't already annotated for nullness by using stub files.
JSR305和FindBugs是由同一个人编写的。两者的维护都很差,但都是标准的,并且得到所有主要ide的支持。好消息是,他们工作得很好。
下面是如何在默认情况下将@Nonnull应用到所有类、方法和字段。
参见https://stackoverflow.com/a/13319541/14731和https://stackoverflow.com/a/9256595/14731
定义@NotNullByDefault
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.annotation.Nonnull;
import javax.annotation.meta.TypeQualifierDefault;
/**
* This annotation can be applied to a package, class or method to indicate that the class fields,
* method return types and parameters in that element are not null by default unless there is: <ul>
* <li>An explicit nullness annotation <li>The method overrides a method in a superclass (in which
* case the annotation of the corresponding parameter in the superclass applies) <li> there is a
* default parameter annotation applied to a more tightly nested element. </ul>
* <p/>
* @see https://stackoverflow.com/a/9256595/14731
*/
@Documented
@Nonnull
@TypeQualifierDefault(
{
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.LOCAL_VARIABLE,
ElementType.METHOD,
ElementType.PACKAGE,
ElementType.PARAMETER,
ElementType.TYPE
})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNullByDefault
{
}
2. 将注释添加到每个包:package-info.java
@NotNullByDefault
package com.example.foo;
更新:截至2012年12月12日,JSR 305被列为“休眠”。根据文档:
被执行委员会投票为“休眠”的JSR,或者已经达到自然生命周期的JSR。
看起来JSR 308正在加入JDK 8,尽管JSR没有定义@NotNull,但是附带的Checkers框架定义了。在撰写本文时,由于这个错误,Maven插件无法使用:https://github.com/typetools/checker-framework/issues/183
如果您正在使用Spring 5。2.执行以下命令:你应该使用Spring注释(org.springframework.lang),因为它们通过@NonNullFields和@NonNullApi注解为你提供了默认的包范围的null检查。当你使用@NonNullFields/@NonNullApi时,你甚至不会与来自其他依赖的其他NotNull/NonNull注释发生冲突。注释必须用在一个名为package-info.java的文件中,该文件位于包的根目录下:
@NonNullFields
@NonNullApi
package org.company.test;
要排除null检查中的某些字段、参数或返回值,只需显式地使用@Nullable注释。而不是使用@NonNullFields/@NonNullApi,你也可以在任何地方设置@NonNull,但可能更好的是在默认情况下使用@NonNullFields/@NonNullApi激活null检查,并且只使用@Nullable执行特定的异常。
IDE (Intellij)将突出显示违反null条件的代码。如果设置正确,每个开发人员都可以假设字段、参数和返回值必须不是空,除非有@Nullable注释。要了解更多信息,请查看这篇文章。