Created
June 24, 2011 16:09
-
-
Save tksk/1045104 to your computer and use it in GitHub Desktop.
Settings by enum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if(Settings._.hasError()){ | |
System.err.println("something wrong."); | |
} | |
System.out.println("main.foo: " + Settings.main$foo.value()); | |
System.out.println("main.bar: " + Settings.main$bar.value()); | |
System.out.println("sub.buz: " + Settings.sub$buz.value()); | |
System.out.println("sub.quux: " + Settings.sub$quux.value()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public enum Settings { | |
_, // dummy | |
main$foo, | |
main$bar, | |
sub$buz("buzval"), | |
sub$quux("quuxval") | |
; | |
private static enum singleton { | |
instance | |
; | |
public boolean hasError = false; | |
Properties props = new Properties(); { | |
try { | |
props.load(new FileInputStream("yourapp.properties")); | |
} catch (Exception e) { | |
hasError = true; | |
} | |
} | |
} | |
private final String defaultValue; | |
private final String key; | |
public String value() { | |
if(hasError()) throw new IllegalStateException("properties haven't been loaded."); | |
return singleton.instance.props.getProperty(key, defaultValue); | |
} | |
public String key() { | |
return key; | |
} | |
public boolean hasError() { | |
return singleton.instance.hasError; | |
} | |
private Settings() { | |
this(null); | |
} | |
private Settings(String defaultValue) { | |
this.defaultValue = defaultValue; | |
this.key = this.name().replace('$', '.'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
main.foo=aaa | |
main.bar=bbb | |
sub.buz=ccc | |
#sub.quux=DEFAULT_VALUE_IS_CHOSEN |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
singleton prevents multiple and unnecessarily loading with below restrictions within enum.