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
参数进行空检查.
您可以使用//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)
您可以使用@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)
归档时间: |
|
查看次数: |
6362 次 |
最近记录: |