java_mouse java_mouse - 5 months ago 20
Java Question

How to initialize Java enum based Singleton?

What is the proper way to initialize java enum based singleton, if I have to initialize it before I can use the object.

I have started writing the code , but I am not sure if I am doing it right. Could you help me to implement this singleton correct for me?

public enum BitCheck {

INSTANCE;

private static HashMap<String, String> props = null;

public synchronized void initialize(HashMap<String, String> properties) {
if(props == null) {
props = properties;
}
}

public boolean isAenabled(){
return "Y".equalsIgnoreCase(props.get("A_ENABLED"));
}

public boolean isBenabled(){
return "Y".equalsIgnoreCase(props.get("B_ENABLED"));
}

}

Answer

It's perfectly possible to create constructor for enum:

public enum BitCheck {

    INSTANCE;

    BitCheck() {
        props = new HashMap<String, String>();
    }

    private final Map<String, String> props;

    //..

}

Note that:

  • props field can be final (we like final)
  • props doesn't have to be static
  • constructor is called automatically and eagerly for you

Pay attention to the last point. Since enum-singletons are created eagerly when the enum BitCheck class is loaded, you have no way to pass any arguments to the constructor. Of course you can through INSTANCE declaration:

public enum BitCheck {

    INSTANCE(new HashMap<String, String>());

    BitCheck(final Map<String, String> props) {
        this.props = props;
    }

but this doesn't make any difference, right? What do you want to achieve? Maybe you actually need lazy-initialized singleton?