java - Initializing a final field in an enum, where the value is loaded through a method which throws an Exception? -



java - Initializing a final field in an enum, where the value is loaded through a method which throws an Exception? -

so i'm trying load image part of constants in inner enum. following:

public enum state { happy, sad; private final image image; }

currently, have loading external constant , static initializer so:

private static final image happy_image; static { image happyimage = null; seek { happyimage = imageio.read(new file("path/to/file.gif")); } catch(ioexception ioe) { logger.fatal("failed 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 utilize approach, though, 2 reasons. first, it's bit more verbose seems necessary. more importantly, creates redundant constant. there's no reason have happy_image when image should accessed via state.happy.getimage().

the next valid, can't assign different value each enum value.

public enum state { happy; private final image image; { image image = null; seek { image = imageio.read(new file("path/to/file.gif")); } catch(ioexception ioe) { logger.fatal("failed load image."); } this.image = image; } }

so there way can accomplish loading of enum's final value?

an enum can have constructor. can loading there.

public enum state { happy("path/image.gif"); private final image image; private state(string path) { this.image = ... } public image getimage() { homecoming image; } }

java enums initialization instance-variables

Comments

Popular posts from this blog

c - Compilation of a code: unkown type name string -

java - Bypassing "final local variable defined in an enclosing type" -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -