我正在尝试为最终图像创建枚举,其中将从文件加载变量“图像”。如果发生 IOException,我希望将“图像”设置为空。然而,根据编译器的说法,当 catch block 运行时,'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 block 只有在没有设置图像时才会运行,但编译器说它可能已被设置)
有没有办法让我在 catch block 中将图像分配给空值,前提是它还没有被设置?
最佳答案
尝试使用局部临时变量:
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;
}
}
关于java - 检测构造函数中的 final 是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35642608/