java property file as enum

前端 未结 8 1086
梦如初夏
梦如初夏 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:09

    One way, I could imagine, to get all the properties in your IDE can be to define an Enum with all of them, like this :

    public enum Settings
    {
       EQUIPMENT_HEIGHT("equipment.height", "0"),
    
       EQUIPMENT_WIDTH("equipment.width", "0"),
    
       EQUIPMENT_DEPTH("equipment.depth", "0");
    
       private String property;
    
       private String value;
    
       Settings(final String aProperty, final String aValue)
       {
          property = aProperty;
          value = aValue;
       }
    
       public String getProperty()
       {
          return property;
       }
    
       public String getValue()
       {
          return value;
       }
    
       private void setValue(final String aValue)
       {
          value = aValue;
       }
    
       public static void initialize(final Properties aPropertyTable)
       {
          for(final Settings setting : values())
          {
             final String key = setting.getProperty();
             final String defaultValue = setting.getValue();
             setting.setValue(aPropertyTable.getProperty(key, defaultValue));
          }
       }
    }
    

    The initialization of the enum is self explained (method initialize()).

    After that, you can use it like this :

    Settings.EQUIPMENT_HEIGHT.getValue();
    

    Adding new property is just adding new enum-Constant.

提交回复
热议问题