有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我正在尝试为最终图像创建一个枚举,变量“image”将从文件中加载。如果发生IOException,我希望将“image”设置为null。然而,根据编译器,当catch块运行时,“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'
        }
    }
}

最终变量需要在构造函数中设置,因此如果由于某种原因无法读取图像,则必须将其设置为某个值。然而,无法判断图像是否已实际设置。(在这种情况下,仅当未设置映像时,catch块才会运行,但编译器说它可能已设置)

是否只有在未设置图像的情况下,才可以在catch块中将图像指定为null


共 (2) 个答案

  1. # 1 楼答案

    尝试使用局部临时变量:

    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;
        }
    }
    
  2. # 2 楼答案

    这是我最终使用的解决方案。它添加了一个方法,这样,如果ImageIO类确实找到了一个图像,代码就会返回,这样就没有机会调用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;
            }
        }
    }
    

    然而,这并不是一种检测空白最终变量的方法。我希望看看是否有办法在try/catch中设置一个最终变量,而不必使用临时变量来解决这个问题