繁体   English   中英

初始化枚举中的final字段,该枚举中的值是通过引发Exception的方法加载的?

[英]Initializing a final field in an enum, where the value is loaded through a method which throws an Exception?

所以我试图加载一个Image作为内部枚举中的常量的一部分。 类似于以下内容:

public enum State {
    HAPPY, SAD; 

    private final Image image;
}

当前,我从外部常量和静态初始化程序加载它,如下所示:

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

但是,出于两个原因,我不想使用这种方法。 首先,它比看起来需要的要冗长一些。 但更重要的是,它创建了一个冗余常数。 通过State.HAPPY.getImage()访问图像时,没有理由拥有HAPPY_IMAGE

以下内容是有效的,但我不能为每个枚举值分配不同的值。

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

那么,有什么方法可以完成对枚举数final值的加载?

一个枚举可以有一个构造函数。 因此,您可以在那里进行加载。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM