java - 声纳错误报告删除这个总是评估为“真”的表达式
问题描述
如果我有这个代码声纳不会抱怨:
if (null != myResponse) {
// some code
}
但是如果我在上面放一行代码
getEmptyListForNull(myResponse).forEach(this::method);
然后声纳报告这个奇怪的错误。声纳如何知道做什么getEmptyListForNull
和那无关紧要。
显然声纳认为代码是这样的:
myResponse.forEach(this::method);
该方法getEmptyListForNull
是一个简单的方法,它进行null
检查并返回一个空列表(如果是)。没有其他注释或任何花哨的东西。
解决方案
实际上 SonarQube 不知道您的功能。这与您的功能无关。它是关于 forEach() 的。
如果您可以使用 .forEach() 迭代集合而不会引发异常,则意味着该集合不为空。
import java.util.List;
public class NoFalsePositiveHere{
public static void main(String []args){
List<String> nullList = null;
nullList.forEach(s -> System.out.println(s));
if(nullList != null){
System.out.println("Since an exception is already thrown on line 9,");
System.out.println("this block is unreachable.");
System.out.println("It means that,");
System.out.println("if no exception was thrown on line 9,");
System.out.println("You could see these lines on console.");
}
}
}
如果第 9 行抛出异常,则不执行第 11 行。
如果第 9 行没有抛出异常,则表示该列表不为空。
推荐阅读
- video - FileSystemWatcher 未检测到 mp4 文件
- angular - 您的应用程序将仅部署在由提供的索引或标识符指定的设备上
- javascript - Django Rest Framework - 错误请求
- vb.net - 获取当前使用指定端口号的IP地址
- android - 错误:需要 Gradle 版本 2.2。当前版本是 5.1.1
- java - 我试图将 EC 公钥从 android 导出到 iOS,最好的方法是什么?
- html - 如何将页面详细信息值添加到 SharePoint 页脚
- opencv - find4QuadCornerSubpix 与cornerSubPix
- c++ - 我可以依靠 TCHAR 的定义来对我正在使用的字符集做出正确的假设吗?
- javascript - 有没有办法强制在同一路由中重新加载路由器视图组件?