Skip to content

Instantly share code, notes, and snippets.

@tksk
Created June 24, 2011 16:09
Show Gist options
  • Save tksk/1045104 to your computer and use it in GitHub Desktop.
Save tksk/1045104 to your computer and use it in GitHub Desktop.
Settings by enum
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());
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('$', '.');
}
}
main.foo=aaa
main.bar=bbb
sub.buz=ccc
#sub.quux=DEFAULT_VALUE_IS_CHOSEN
@tksk
Copy link
Author

tksk commented Jun 24, 2011

singleton prevents multiple and unnecessarily loading with below restrictions within enum.

  1. enum cannot contain static fields
  2. instance fields are initialized for each entries in the enum itself

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment