Search code examples
javamavenjavafxspotbugs

ImageView causing UI_INHERITANCE_UNSAFE_GETRESOURCE error from Spotbugs


I am trying to create an ImageView with an Image object which displays a .jpg picture. When I run "mvn clean install", this is the error message I receive:

UI_INHERITANCE_UNSAFE_GETRESOURCE

I am futhermore provided with this information:

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]

I have absolutely no idea how else I can add .jpg files to my project. The pathing is correct. I am able to launch my application when using the built in java run method, (Right click and run), without it crashing.

Here is the piece of code which causes the crash:

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

The only "warning" message that IntelliJ provides is to add Objects.requireNonNull before getClass.getResource...

I assume this either is a Spotbugs problem, but they provide no possible solution or workaround. How do I fix this problem?


Solution

  • The warning says:

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

    So one solution is to not allow the class to be extended.

    Make the class final

    A class that is declared final cannot be subclassed.

    For example, by putting the final keyword in front of the class declaration:

    final class MyClass {
        // implementation methods.
    }
    

    Another solution may be to directly reference the class by name rather than getClass() when retrieving a resource.

    For example, replace:

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

    with:

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

    All that said, I have never seen a warning about resource lookup like that and believe that, unless you better understand the reason for it and are operating in an environment that must be incredibly secure (slot machine implementation may qualify), then it could be safely ignored for most applications.