SonarQube 质量失败,方法中可能存在 NullPointer
调用该方法时,我正在检查 !=null,但没有传递
private Asset findAsset(List<Asset> assets, Long assetId) {
return assets.parallelStream()
.filter(ast -> ast.getAssetId().equals(assetId))
.findFirst()
.orElse(null);
}
我正在尝试以下代码:
if (findAsset(assetCompositionList, pair.getKey()) != null) {
assetMap.put(pair.getKey(),
findAsset(assets, pair.getKey()).getAssetCode());
}
调用时我已经在 findAsset()
方法中检查 !=null
。
最佳答案
第二次调用 findAsset
函数时出现错误。
assetMap.put(pair.getKey(), findAsset(assets,pair.getKey()).getAssetCode());
首先将结果收集到变量中,然后检查是否为 null。
Asset asset = findAsset(assetCompositionList, pair.getKey());
if (asset != null) {
assetMap.put(pair.getKey(), asset.getAssetCode());
}
由于您调用方法两次,因此在第一次调用时存在空检查,但在第二次调用时,没有空检查。 Sonar 不够智能,无法检查多个函数调用中传递的相同参数。
关于java - 使用 findFirst 时,sonarqube Nullpointer 的质量检查失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55435190/