简体   繁体   中英

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. 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() .

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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