java property file as enum

前端 未结 8 1079
梦如初夏
梦如初夏 2020-12-24 09:47

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
e         


        
相关标签:
8条回答
  • 2020-12-24 10:29

    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);
    
    0 讨论(0)
  • 2020-12-24 10:31

    no, I don't think so. Enums are creating in compile time and thus their number of elements cannot vary depending on whatever it is in the property file.

    It's more likely that you would need an structure that is flexible to be constructed in runtime - maybe an associative array.

    0 讨论(0)
提交回复
热议问题