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 ?