[英]Initializing a final field in an enum, where the value is loaded through a method which throws an Exception?
So I'm trying to load an Image
as part of the constants in an inner enum. 所以我试图加载一个Image
作为内部枚举中的常量的一部分。 Something like the following: 类似于以下内容:
public enum State {
HAPPY, SAD;
private final Image image;
}
Currently, I have it loading from an external constant and a static initializer like so: 当前,我从外部常量和静态初始化程序加载它,如下所示:
private static final Image HAPPY_IMAGE;
static {
Image happyImage = null;
try {
happyImage = ImageIO.read(new File("path/to/file.gif"));
}
catch(IOException ioe) {
LOGGER.fatal("Failed to load image.");
}
HAPPY_IMAGE = happyImage;
}
public enum State {
HAPPY (HAPPY_IMAGE);
private final Image image;
private State(Image image) {
this.image = image;
}
}
I don't want to use this approach, though, for two reasons. 但是,出于两个原因,我不想使用这种方法。 First, it's a bit more verbose than seems necessary. 首先,它比看起来需要的要冗长一些。 But more importantly, it creates a redundant constant. 但更重要的是,它创建了一个冗余常数。 There's no reason to have HAPPY_IMAGE
when the image should be accessed via State.HAPPY.getImage()
. 通过State.HAPPY.getImage()
访问图像时,没有理由拥有HAPPY_IMAGE
。
The following is valid, but I can't assign a different value for each enum value. 以下内容是有效的,但我不能为每个枚举值分配不同的值。
public enum State {
HAPPY;
private final Image image;
{
Image image = null;
try {
image = ImageIO.read(new File("path/to/file.gif"));
}
catch(IOException ioe) {
LOGGER.fatal("Failed to load image.");
}
this.image = image;
}
}
So is there any way I can accomplish this loading of the enum's final
value? 那么,有什么方法可以完成对枚举数final
值的加载?
An enum can have a constructor. 一个枚举可以有一个构造函数。 So you can do the loading there. 因此,您可以在那里进行加载。
public enum State {
HAPPY("path/image.gif");
private final Image image;
private State(String path)
{
this.image = ...
}
public Image getImage()
{
return image;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.