java枚举中的重复代码

标签 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;

    ...

}

最佳答案

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

  1. 使用发布这些常量和不可变值的类
  2. 从属性文件生成java源代码
  3. 使用反射生成java代码

我建议选择 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);
    }

}

关于java枚举中的重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36980903/

相关文章:

java - 将 Int 转换为 Java 中的枚举

java - NetBeans 12 UTF-8 中文输出与 Maven 项目

Java类方法没有初始化

java - 如何获得小数点后 4 位的输出答案

java - 模仿 JTable 中行呈现的默认行为

ios - 在 Swift 3.1 中使用自定义 Setter 更新数组属性

python - 强制子类实现属性python

php - 如何使用变量访问动态属性?

c++ - 为枚举参数化的模板

swift - 基于字符串的枚举是否有 Swift 类型?