如何告诉IDEA/Studio已完成空检查?

Ben*_*fez 8 intellij-idea android-studio

我正在开发Android Studio/IntelliJ IDEA.

我已启用名为"常量条件和例外"的检查检查,如果我冒着NPE的风险,则显示警告,例如:

String foo = foo.bar(); // Foo#bar() is @nullable
if (foo.contains("bar")) { // I'm living dangerously
    ...
}
Run Code Online (Sandbox Code Playgroud)

我的代码中有以下内容:

String encoding = contentEncoding == null ? null : contentEncoding.getValue();
if (!TextUtils.isEmpty(encoding) && encoding.equalsIgnoreCase("gzip")) {
    inputStream = new GZIPInputStream(entity.getContent());
} else {
    inputStream = entity.getContent();
}
Run Code Online (Sandbox Code Playgroud)

这是源代码TextUtils#isEmpty(String):

/**
 * Returns true if the string is null or 0-length.
 * @param str the string to be examined
 * @return true if str is null or zero length
 */
public static boolean isEmpty(CharSequence str) {
    if (str == null || str.length() == 0)
        return true;
    else
        return false;
}
Run Code Online (Sandbox Code Playgroud)

我没有冒任何NPE的风险,因为它TextUtils#isEmpty(String)会返回null指针.

但是我仍然得到一点Method invocation 'encoding.equalsIgnoreCase("gzip")' may produce 'java.lang.NullPointerException'警告,这可能很烦人.

如果已经进行了空检查,是否可以使此检查更智能并忽略NPE警告?

mab*_*aba 18

您可以查看Peter Gromov在答案中提到的链接.

创建了一些类似于您的设置的简单类:

带有注释方法的类@Nullable:

在此输入图像描述

TextUtil用它的isEmpty方法的类:

在此输入图像描述

最后主要的类叫TextUtil#isEmpty:

在此输入图像描述

现在,如果您输入File -> Settings...并转到Inspections ->Constant conditions & exceptions零件,您可以更改Configure Assert/Check Methods为您的isEmpty方法来满足:

在此输入图像描述

添加新的IsNull检查方法:

在此输入图像描述

输入TextUtil类,isEmpty方法和CharSequence参数:

在此输入图像描述

这给出了这个Assert/Check Method Configuration窗口:

在此输入图像描述

Ok,然后Ok再返回编辑器视图,您将看到检查消失:

在此输入图像描述

您实际上是告诉IntelliJ该isEmpty方法正在对str参数进行空检查.

  • 似乎至少在 Android Studio 1.2.2 中没有这样的选项(配置断言/检查方法) (3认同)

Oli*_*yen 9

您可以使用//noinspection ConstantConditions它将删除以下行的NPE警告,如下所示:

String encoding = contentEncoding == null ? null : contentEncoding.getValue();

//noinspection ConstantConditions
if (!TextUtils.isEmpty(encoding) && encoding.equalsIgnoreCase("gzip")) {
    inputStream = new GZIPInputStream(entity.getContent());
} else {
    inputStream = entity.getContent();
}
Run Code Online (Sandbox Code Playgroud)


jk2*_*k2K 5

您可以使用@SuppressWarnings("ConstantConditions")注释。

@SuppressWarnings("ConstantConditions")
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int indexViewType) {
    if (inflater == null) {
        inflater = LayoutInflater.from(parent.getContext());
    }
    ItemViewProvider provider = getProviderByIndex(indexViewType);
    provider.adapter = MultiTypeAdapter.this;
    return provider.onCreateViewHolder(inflater, parent);
}
Run Code Online (Sandbox Code Playgroud)