Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java property file as enum

Tags:

java

Is it possible to convert a property file into an enum.

I have a propoerty file with lot of settings. for example

equipment.height
equipment.widht
equipment.depth 
and many more like this and not all are as simple as the example

The developer has to know the key in order to get the value of the property. instead is it possible to do something, where the developer would type MyPropertyEnum. and the list of keys will show up in the IDE, like it shows up for an Enum

MyPropertyEnum.height
like image 208
user373201 Avatar asked Feb 05 '11 19:02

user373201


2 Answers

I often use property file + enum combination. Here is an example:

public enum Constants {
    PROP1,
    PROP2;

    private static final String PATH            = "/constants.properties";

    private static final Logger logger          = LoggerFactory.getLogger(Constants.class);

    private static Properties   properties;

    private String          value;

    private void init() {
        if (properties == null) {
            properties = new Properties();
            try {
                properties.load(Constants.class.getResourceAsStream(PATH));
            }
            catch (Exception e) {
                logger.error("Unable to load " + PATH + " file from classpath.", e);
                System.exit(1);
            }
        }
        value = (String) properties.get(this.toString());
    }

    public String getValue() {
        if (value == null) {
            init();
        }
        return value;
    }

}

Now you also need a property file (I ofter place it in src, so it is packaged into JAR), with properties just as you used in enum. For example:

constants.properties:

#This is property file...
PROP1=some text
PROP2=some other text

Now I very often use static import in classes where I want to use my constants:

import static com.some.package.Constants.*;

And an example usage

System.out.println(PROP1);
like image 51
Sebastian Łaskawiec Avatar answered Sep 21 '22 12:09

Sebastian Łaskawiec


Java has static typing. That means, you can't create types dynamically. So, the answer is no. You can't convert a property file into a enum.

What you could do is generate an enum from that properties file. Or, use a Dictionary (Map) to access your properties with something like:

equipment.get("height");
like image 39
Pablo Santa Cruz Avatar answered Sep 21 '22 12:09

Pablo Santa Cruz