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

Unboxing of cameraCharacteristics may produce Nullpointer Exception and FindBugs

我无法处理以下导致 FindBugs 引发错误的警告。

我正在使用相机2 api。 如您所见,我已经在检查 null 并另外捕获可能的 NullPointer 异常。 CameraCharacteristics class 的 .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) 将 return null 那么自动装箱将产生 NPE 因为 null 无法转换为原始 int.

这里有一些有趣的东西 article

您可以将 variables/fields 重构为 Wrapper 类,例如 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;
            }
        }