取消对照相机特征的装箱操作可能会产生Nullpointer异常和FindBugs

时间:2018-08-13 14:52:41

标签: java android annotations findbugs unboxing

我无法处理以下导致 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分析中。

1 个答案:

答案 0 :(得分:2)

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

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

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

这里有一些有趣的article

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

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;
            }
        }