我希望使我的代码更具可读性,以及使用工具,如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


当前回答

One of the nice things about IntelliJ is that you don't need to use their annotations. You can write your own, or you can use those of whatever other tool you like. You're not even limited to a single type. If you're using two libraries that use different @NotNull annotations, you can tell IntelliJ to use both of them. To do this, go to "Configure Inspections", click on the "Constant Conditions & Exceptions" inspection, and hit the "Configure inspections" button. I use the Nullness Checker wherever I can, so I set up IntelliJ to use those annotations, but you can make it work with whatever other tool you want. (I have no opinion on the other tools because I've been using IntelliJ's inspections for years, and I love them.)

其他回答

JSpecify将是一种方法(当它准备好时)。事实上,他们的陈述积极地与这个问题联系在一起,并明确表示他们的目标是最终得到一个好的答案。

它拥有Android、Guava和Kotlin等主要参与者。

在等待上游(Java 8?)整理这些注释时,您还可以定义自己的项目本地@NotNull和@Nullable注释。这在使用Java SE时也很有用,因为默认情况下javax.validation.constraints是不可用的。

import java.lang.annotation.*;

/**
 * Designates that a field, return value, argument, or variable is
 * guaranteed to be non-null.
 */
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})
@Documented
@Retention(RetentionPolicy.CLASS)
public @interface NotNull {}

/**
 * Designates that a field, return value, argument, or variable may be null.
 */
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})
@Documented
@Retention(RetentionPolicy.CLASS)
public @interface 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.

对于Android项目,您应该使用Android .support.annotation. nonnull和Android .support.annotation. nullable。这些和其他有用的特定于android的注释在支持库中可用。

从http://tools.android.com/tech-docs/support-annotations:

支持库本身也使用这些注释 注解,所以作为支持库的用户,Android Studio将 检查您的代码并基于这些标记潜在的问题 注释。

如果你正在使用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注释是无用的。