7

Instead of the usual if (myString == null || myString.equals("")) I tend to prefer using the org.apache.commons.lang.StringUtils class and do if (StringUtils.isEmpty(myString)).

However this - at least the way I'm doing it - comes with a gigantic downside: because FindBugs - or the compiler warning mechanism, f. ex. from Eclipse - will no longer see the explicit null-check, it will no longer consider myString as potentially null, so it will no longer raise the warnings about potential (or sure) null pointers on it, and those warnings are extremely useful in my view.

Example (ADDED):

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"
    }
}

So I'm just trying to make sure that there is no way to eliminate or minimize this downside so that one can use StringUtils.isEmpty and still get the null pointer warnings. Maybe some annotation like @Nullcheck to add to the isEmpty method or something else ?

ADDED: For ex., would it be feasible to create a custom annotation like @Nullcheck, add it to the arg of isEmpty like public static boolean isEmpty(@Nullcheck String str) just to indicate that the method does a null-check on that arg, and make so that the compiler warning mechanism or FindBugs treat a if (StringUtils.isEmpty(myString)) just like an explicit null-check ?

4

3 回答 3

1

如果你用@Nullable 注释myString,即

void testWarning(@Nullable String myString)

那么当你取消引用它时,至少eclipse会报告一个警告。

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

于 2014-06-16T21:35:03.130 回答
1

您是否收到潜在的空指针警告实际上取决于静态代码分析器的性能。从逻辑上讲,如果您使用

if (myString == null || myString.equals(""))

您的代码期望 myString 为空。但是,在下一行中,您取消引用 myString。静态代码分析器看到这两个事实,并创建一个空指针警告。

如果你使用

if (StringUtils.isEmpty(myString))

您的代码没有说明它是否期望 myString 为空。因此,静态代码分析器不会生成空指针警告。静态代码分析器当然可以选择生成空指针警告,但这会产生很多误报,因为它需要假设任何方法的输入都可能为空。

于 2014-06-09T13:07:25.943 回答
1

Eclipse 代码分析还可以评估外部空注释(从 4.5.0 开始)。更多信息可在https://wiki.eclipse.org/JDT_Core/Null_Analysis/External_Annotations获得。

于 2015-11-23T17:46:08.197 回答