检测构造函数中的 final 是否为空

Detecting if a final is blank in a constructor

我正在尝试为最终图像创建枚举,其中将从文件加载变量 'image'。如果发生 IOException,我希望将 'image' 设置为 null。但是,根据编译器,当捕获块 运行 时,可能会或可能不会设置 'image'。

public enum Tile {
    GROUND("ground.png"), WALL("wall.png");
    final Image image;
    Tile(String filename) {
        try {
            image = ImageIO.read(new File("assets/game/tiles/" + filename));
        } catch (IOException io) {
            io.printStackTrace();
            image= null; // compiler error 'image may already have been assigned'
        }
    }
}

final 变量需要在构造函数中设置,所以如果由于某种原因无法读取图像,则必须将其设置为某些内容。但是,无法判断图像是否已实际设置。 (在这种情况下,如果没有设置图像,catch 块只会 运行,但编译器说它可能已被设置)

有没有办法让我在 catch 块中将图像分配给空值,前提是它没有被设置?

尝试使用局部临时变量:

public enum Tile {
    GROUND("ground.png"), WALL("wall.png");
    final Image image;
    Tile(String filename) {

        Image tempImage;
        try {
            tempImage= ImageIO.read(new File("assets/game/tiles/" + filename));
        } catch (IOException io) {
            io.printStackTrace();
            tempImage= null; // compiler should be happy now.
        }

        image = tempImage;
    }
}

这是我最终使用的解决方案。它添加了一个方法,以便代码 return 如果 ImageIO class 确实找到了图像,则没有机会调用 catch 语句。

public enum Tile {
    GROUND("ground.png"), WALL("wall.png");
    final Image image;
    Tile(String filename) {
        image = getImage(filename);
    }
    Image getImage(String filename) {
        try {
            return ImageIO.read(new File("assets/game/tiles/" + filename));
        } catch (IOException io) {
            io.printStackTrace();
            return null;
        }
    }
}

但是,这并不是检测空白 final 变量的真正方法。我希望看看是否有办法在 try/catch 中设置最终变量,而无需使用临时变量解决问题。