使用StringUtils.isEmpty而不会丢失有关空指针的编译器警告

San*_*ors 7 java findbugs apache-commons compiler-warnings null-pointer

而不是通常if (myString == null || myString.equals(""))我倾向于使用org.apache.commons.lang.StringUtils类和做if (StringUtils.isEmpty(myString)).

然而,这 - 至少我正在做的方式 - 带来了巨大的缺点:因为FindBugs - 或编译器警告机制,f.恩.来自Eclipse - 将不再看到显式的空检查,它将不再被myString视为可能为null,因此它将不再引发关于它的潜在(或确定)空指针的警告,并且这些警告在我的视图中非常有用.

示例(已添加):

import org.apache.commons.lang.StringUtils;

public class TestWarning
{
    void testWarning(String myString)
    {
        //if (myString == null || myString.equals("")) // With this, the last line shows the warning.
        if (StringUtils.isEmpty(myString)) // With this, no warning.
        {
            // Anything.
        }
        int x = myString.length(); // Warning is here: "Potential null pointer access: The variable myString may be null at this location"
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我只是想确保没有办法消除或最小化这个缺点,以便人们可以使用StringUtils.isEmpty并仍然获得空指针警告.也许一些注释喜欢@Nullcheck添加到isEmpty方法或其他东西?

增加:恩,那会是创建一个自定义注释一样可行.@Nullcheck,将它添加到arg的isEmpty喜欢public static boolean isEmpty(@Nullcheck String str)只是为了表明该方法确实对ARG空检查,并作出这样编译器警告机制或FindBugs的治疗一个if (StringUtils.isEmpty(myString))就像是一个明确的空检查?

Tim*_*imK 1

如果你用@Nullable注释myString,即

void testWarning(@Nullable String myString)
Run Code Online (Sandbox Code Playgroud)

那么当您取消引用它时,至少 Eclipse 会报告警告。

我同意 FindBugs 也应该对此发出警告,但我也无法让它这样做。