简体   繁体   English

IntelliJ null检查警告

[英]IntelliJ null check warnings

I often have code like this: 我经常有这样的代码:

protected @Nullable Value value;

public boolean hasValue() { return value != null; }

the problem with this is that when I do null checks like so: 这个问题是,当我做这样的空检查时:

if (!hasValue()) throw...
return value.toString();

then IntelliJ will warn me about a possible NPE 然后IntelliJ会警告我可能的NPE

whereas

if (value != null) throw...
return value.toString();

avoids this warning. 避免这个警告。

is there a way to decorate my hasValue() method so that IntelliJ knows it does a null check? 有没有办法装饰我的hasValue()方法,以便IntelliJ知道它进行空检查? and won't display the warning? 并且不会显示警告?

Intellij-Jetbrains is very clever IDE and itself suggests you way for solving many problems. Intellij-Jetbrains是一个非常聪明的IDE,它本身就是你解决许多问题的方法。

Look at screenshot below. 看下面的截图。 It suggests your five ways for removing this warning: 它建议您删除此警告的五种方法:

1) add assert value != null ; 1)添加assert value != null ;

2) replace return statement with return value != null ? value.toString() : null; 2)用return value != null ? value.toString() : null;替换return语句return value != null ? value.toString() : null; return value != null ? value.toString() : null;

3) surround with 3)环绕着

    if (value != null) {
        return value.toString();
    }

4) suppress inspection for this particular statement by adding commentary: 4)通过添加评论来抑制对此特定陈述的检查:

//noinspection ConstantConditions
return value.toString();

5) add at least, as earlier @ochi suggested use @SuppressWarnings("ConstantConditions") annotation which can be used for method or for whole class. 5)至少添加,因为之前的@ochi建议使用@SuppressWarnings("ConstantConditions")注释,它可以用于方法或整个类。

To invoke this context menu use shortcut keys Alt+Enter (I think they are common for all OS). 要调用此上下文菜单,请使用快捷键Alt+Enter (我认为它们对所有操作系统都是通用的)。

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM