我正在使用 Android Studio/IntelliJ IDEA 进行开发。
我启用了名为“恒定条件和异常”的检查检查,如果我冒着 NPE 的风险,它会显示警告,例如:
String foo = foo.bar(); // Foo#bar() is @nullable
if (foo.contains("bar")) { // I'm living dangerously
...
}
我的代码中有以下内容:
String encoding = contentEncoding == null ? null : contentEncoding.getValue();
if (!TextUtils.isEmpty(encoding) && encoding.equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(entity.getContent());
} else {
inputStream = entity.getContent();
}
下面是源代码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;
}
我不会冒任何 NPETextUtils#isEmpty(String)
的风险,因为会返回 truenull
指针。
但是我仍然得到一点点Method invocation 'encoding.equalsIgnoreCase("gzip")' may produce 'java.lang.NullPointerException'
警告,这可能很烦人。
如果已经完成了空检查,是否可以使此检查更智能并忽略 NPE 警告?