枚举中的java重复代码

时间:2016-05-02 11:03:48

标签: java properties enums

我的程序中有重复的代码,我有枚举从属性文件加载值,我想让我的代码更清晰。

也许Interface可以作为解决方案,但我无法宣布非最终变量。

这是一个例子:

public enum AlertMessageEnum{
    //
    OUTPUT_FOLDER_EXISTS, 
    ...
    CONFIG_FILE_IS_MISSING;
    // the file path to load properties
    private static final String PATH= "/i18n/alertDialogText.properties";
    private static Properties   properties;
    private String value;

    public void init() {
        if (properties == null) {
            properties = new Properties();
            try {
                properties.load(AlertMessageEnum.class.getResourceAsStream(PATH));
            }
            catch (Exception e) {
                throw new RthosRuntimeException(e);
            }
        }
        value = (String) properties.get(this.toString());
    }

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

public enum ConverterErrorEnum{
    INVALID_EXTRACTION_PATH,
    ...
    PATIAL_DATA_GENERATED;

    private static final String PATH= "/i18n/converterErrorText.properties";
    private static Properties   properties;
    private String value;

    ...

}

2 个答案:

答案 0 :(得分:0)

使用普通的java代码从属性文件生成枚举是不可能的。您需要一种解决方法,例如:

  1. 使用一个发布这些常量aws不可变值的类
  2. 从属性文件
  3. 生成java源代码
  4. 使用反射生成java代码
  5. 我建议选项1.例如与单身人士:

    package com.example;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.List;
    import java.util.Properties;
    
    public class Props {
    
        private static Props INSTANCE;
    
        public synchronized Props getInstance() {
            if (INSTANCE == null) {
                INSTANCE = new Props();
            }
            return INSTANCE;
        }
    
        private static final String PATH = "/i18n/converterErrorText.properties";
        private Properties properties;
        private List<String> keys;
    
        public Props() {
            properties = new Properties();
            keys = new ArrayList<>();
            try {
                properties.load(getClass().getResourceAsStream(PATH));
                for (Object key : properties.keySet()) {
                    keys.add(key.toString());
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
        public Enumeration<Object> getKeys() {
            return properties.keys();
        }
    
        public String getProperty(String key) {
            return properties.getProperty(key);
        }
    
    }
    

答案 1 :(得分:0)

委托另一个持有所有Properties的{​​{1}}的类:

enum