IntelliJ null检查警告

yco*_*omp 6 java annotations jetbrains-ide intellij-idea

我经常有这样的代码:

protected @Nullable Value value;

public boolean hasValue() { return value != null; }
Run Code Online (Sandbox Code Playgroud)

这个问题是,当我做这样的空检查时:

if (!hasValue()) throw...
return value.toString();
Run Code Online (Sandbox Code Playgroud)

然后IntelliJ会警告我可能的NPE

if (value != null) throw...
return value.toString();
Run Code Online (Sandbox Code Playgroud)

避免这个警告.

有没有办法装饰我的hasValue()方法,以便IntelliJ知道它进行空检查?并且不会显示警告?

And*_*niy 4

Intellij-Jetbrains 是非常聪明的 IDE,它本身就为您提供了解决许多问题的方法。

看下面的截图。它建议您消除此警告的五种方法:

1)添加assert value != null

2) 将 return 语句替换为return value != null ? value.toString() : null;

3) 围绕

    if (value != null) {
        return value.toString();
    }
Run Code Online (Sandbox Code Playgroud)

4) 通过添加注释来抑制对此特定语句的检查:

//noinspection ConstantConditions
return value.toString();
Run Code Online (Sandbox Code Playgroud)

5)至少添加,正如之前 @ochi 建议使用@SuppressWarnings("ConstantConditions")可用于方法或整个类的注释。

要调用此上下文菜单,请使用快捷键Alt+Enter(我认为它们对于所有操作系统都是通用的)。

在此输入图像描述

  • 所有这些技术确实阻止了 IntelliJ 发出警告。然而,它们都没有回答确保“IntelliJ 知道它 [hasValue] 执行空检查”的原始问题。其他一些工具具有更复杂的代码分析,并支持后置条件注释 [`@EnsuresNonNullIf`](https://checkerframework.org/api/org/checkerframework/checker/nullness/qual/EnsuresNonNullIf.html),它可以完成原始海报的操作问——但不幸的是 IntelliJ 目前没有。 (4认同)