IntelliJ null检查警告 [英] IntelliJ null check warnings

查看:1420
本文介绍了IntelliJ null检查警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常有这样的代码:

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();

然后IntelliJ会警告我可能的NPE

then IntelliJ will warn me about a possible NPE

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

避免此警告。

在那里一种装饰我的 hasValue()方法的方法,以便IntelliJ知道它进行空检查?并且不会显示警告?

is there a way to decorate my hasValue() method so that IntelliJ knows it does a null check? and won't display the warning?

推荐答案

Intellij-Jetbrains是一个非常聪明的IDE,它本身就是你解决许多问题的方法。

Intellij-Jetbrains is very clever IDE and itself suggests you way for solving many problems.

请看下面的截图。它建议你删除此警告的五种方法:

Look at screenshot below. It suggests your five ways for removing this warning:

1)添加断言值!= null ;

2)用替换return语句返回值!= null? value.toString():null;

3)环绕

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

4)通过添加评论来抑制对此特定陈述的检查:

4) suppress inspection for this particular statement by adding commentary:

//noinspection ConstantConditions
return value.toString();

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

5) add at least, as earlier @ochi suggested use @SuppressWarnings("ConstantConditions") annotation which can be used for method or for whole class.

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

To invoke this context menu use shortcut keys Alt+Enter (I think they are common for all OS).

这篇关于IntelliJ null检查警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆