ImageView 导致来自 Spotbugs 的 UI_INHERITANCE_UNSAFE_GETRESOURCE 错误

ImageView causing UI_INHERITANCE_UNSAFE_GETRESOURCE error from Spotbugs

我正在尝试使用显示 .jpg 图片的 Image 对象创建 ImageView。当我 运行“mvn clean install”时,这是我收到的错误消息:

UI_INHERITANCE_UNSAFE_GETRESOURCE

我还获得了以下信息:

Usage of GetResource in ui.SlotsDisplay.createImageView(String) may be unsafe if class is extended [ui.SlotsDisplay] At SlotsDisplay.java:[line 106] UI_INHERITANCE_UNSAFE_GETRESOURCE [INFO]

我完全不知道我还能如何将 .jpg 文件添加到我的项目中。路径是正确的。使用内置的 java 运行 方法(右键单击和 运行)时,我能够启动我的应用程序,而不会崩溃。

这是导致崩溃的代码片段:

private ImageView createImageView(String imageName){
        ImageView imageView = new ImageView(new Image(getClass().getResourceAsStream("/images/cards/" + imageName + ".jpg")));
        imageView.setFitWidth(148);
        imageView.setFitHeight(210);
        return imageView;
    } 

IntelliJ 提供的唯一“警告”消息是在 getClass.getResource 之前添加 Objects.requireNonNull...

我假设这是一个 Spotbugs 问题,但他们没有提供可能的解决方案或解决方法。我该如何解决这个问题?

警告说:

GetResource in ui.SlotsDisplay.createImageView(String) may be unsafe if class is extended

所以一种解决方案是不允许扩展 class。

Make the class final

A class that is declared final cannot be subclassed.

例如,将 final 关键字放在 class 声明前面:

final class MyClass {
    // implementation methods.
}

另一种解决方案可能是在检索资源时通过名称直接引用 class 而不是 getClass()。

例如替换为:

getClass().getResourceAsStream("/images/cards/" + imageName + ".jpg")

与:

SlotsDisplay.class.getResourceAsStream("/images/cards/" + imageName + ".jpg")

综上所述,我从未见过这样的关于资源查找的警告,我相信,除非你更好地理解它的原因并且在必须非常安全的环境中运行(老虎机实施可能符合条件) , 那么对于大多数应用程序可以安全地忽略它。