gpt4 book ai didi

java - 拆箱cameraCharacteristics可能会产生Nullpointer Exception和FindBugs

转载 作者:行者123 更新时间:2023-12-01 19:49:55 28 4
gpt4 key购买 nike

我无法处理以下警告,这会导致 FindBugs 抛出错误。

Error

我正在使用camera2 api。正如您所看到的,我已经在检查 null 并另外捕获可能的 NullPointer 异常。 CameraCharacteristics 类的 .get 方法使用 Nullable 进行注释,因此会出现此错误。我不知道如何防止这种情况。检查 null 似乎无法完成这项工作。

同时,我将 SuppressFBWarnings 注释添加到我的项目中。但即使我像这样抑制警告:

@SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH")
private void setUpCamera(int width, int height) {
try {
for (String cameraId : cameraManager.getCameraIdList()) {
CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId);

if (cameraCharacteristics != null && cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) != null) {
int lensFaceingCameraCharacteristics = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING);

if (cameraFacing == lensFaceingCameraCharacteristics) {
StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
previewSize = getPreviewSize(streamConfigurationMap.getOutputSizes(SurfaceTexture.class), width, height);
this.cameraId = cameraId;
}
}
}
} catch (CameraAccessException | NullPointerException eae) {
Logger.error(eae.getMessage());
}
}

FindBugs 分析中仍然出现错误。

最佳答案

这是一个自动装箱陷阱。让我们看一下这一行:

int lensFaceingCameraCharacteristics = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING);

如果cameraCharacteristics.get(CameraCharacteristics.LENS_FACING)将返回null,则自动装箱将产生NPE,因为null strong> 无法转换为原始 int

这里有一些有趣的article .

您可以将变量/字段重构为包装类,例如IntegerFloat等。

private Integer cameraFacing;

但在这种情况下,您可能需要解决一些新的 NPE 警告。所以你可以像这样重构代码:

 if (cameraCharacteristics != null && cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) != null) {
Integer lensFaceingCameraCharacteristics = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING);

if (lensFaceingCameraCharacteristics != null
&& cameraFacing == lensFaceingCameraCharacteristics) {
StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
previewSize = getPreviewSize(streamConfigurationMap.getOutputSizes(SurfaceTexture.class), width, height);
this.cameraId = cameraId;
}
}

关于java - 拆箱cameraCharacteristics可能会产生Nullpointer Exception和FindBugs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51825127/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com