Skip to content

Instantly share code, notes, and snippets.

@alexsobiek
Last active April 22, 2021 08:42
Show Gist options
  • Save alexsobiek/337d545dfcf46125bf463438591ec539 to your computer and use it in GitHub Desktop.
Save alexsobiek/337d545dfcf46125bf463438591ec539 to your computer and use it in GitHub Desktop.
Super simple Java configuration using an enum

Java Enum Config

I created this simple java configuration enum and utility class to easily retrieve and set config values.

Code

Config.java

public enum Config {
    AGE(10),
    HELLO_WORLD("Hello World");

    Object value;
    Config(Object value) {
        this.value = value;
    }

    Object getValue() {
        return value;
    }

    public static Object get(Config key) {
        if (ConfigUtility.get(key) != null) return ConfigUtility.get(key);
        else return key.getValue();
    }

    public static int getInt(Config key) {
        return (int) get(key);
    }

    public static String getString(Config key) {
        return (String) get(key);
    }

    void set(Object value) {
        ConfigUtility.set(this, value);
    }
}

class ConfigUtility {
    private static final HashMap<Config, Object> overrides = new HashMap<>();
    public static Object get(Config key) {
        return overrides.getOrDefault(key, null);
    }
    public static void set(Config key, Object value) {
        overrides.put(key, value);
    }
}

Usage Example

HelloWorld.java

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println(Config.getString(Config.HELLO_WORLD));
    System.out.println("I am " + Config.getInt(Config.AGE) + " years old!");
    System.out.println();
    Config.AGE.set(30);
    System.out.println("You are " + Config.getInt(Config.AGE) + " years old.");
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment