Create enum in Java from the .properties file

6

Is it possible to load values for an enum from the .properties file? into an enum.

I have the following information in the file called secure.properties:

authorization-api-context=http://localhost:8099/
mongo-db-name=secure
defaul-countries="COL;ARG;PER"

and I would like to create an enum with the default countries, for example:

public enum DefaultCountries {

    COL("COL", "Colombia"), 
    ARG("ARG", "Argentina"),
    PER("PER", "Perú");
    ...
    
asked by AndreFontaine 03.07.2016 в 02:44
source

1 answer

1

Let's see if this helps you:

    public enum Constants {
    PROP1,
    PROP2;

    private static final String PATH = "/constantes.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("No se pudo cargar el archivo " + PATH + " desde esa ruta.", e);
                System.exit(1);
            }
        }
        value = (String) properties.get(this.toString());
    }

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

}

You need a property file with the properties as if you were using them in an enum:

constants.enum:

#Este es el archivo de propiedades...
PROP1=some text
PROP2=some other text

Now you care about the class as static:

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

Example of use:

System.out.println(PROP1);

Reference in English.

    
answered by 06.09.2016 / 00:04
source