我的程序中有重复的代码,我有从属性文件加载值的枚举,我想让我的代码更干净。
也许接口(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 代码不可能从属性文件生成枚举。您需要一个解决方法,例如:
- 使用发布这些常量和不可变值的类
- 从属性文件生成java源代码
- 使用反射生成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/