是否可以将属性文件转换为枚举.
我有一个有很多设置的propoerty文件.例如
equipment.height
equipment.widht
equipment.depth
and many more like this and not all are as simple as the example
Run Code Online (Sandbox Code Playgroud)
开发人员必须知道密钥才能获得属性的价值.相反,它可以做一些事情,开发人员可以输入MyPropertyEnum.并且键列表将显示在IDE中,就像它显示为Enum一样
MyPropertyEnum.height
Run Code Online (Sandbox Code Playgroud)
Seb*_*iec 19
我经常使用属性文件+枚举组合.这是一个例子:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,你还需要一个属性文件(我ofter放置在SRC,所以它被打包成JAR),只有当你在枚举使用的属性.例如:
constants.properties:
#This is property file...
PROP1=some text
PROP2=some other text
Run Code Online (Sandbox Code Playgroud)
现在我经常在我想使用常量的类中使用静态导入:
import static com.some.package.Constants.*;
Run Code Online (Sandbox Code Playgroud)
并举例说明
System.out.println(PROP1);
Run Code Online (Sandbox Code Playgroud)
Java有静态类型.这意味着,您无法动态创建类型.所以,答案是否定的.您无法将属性文件转换为枚举.
你可以做的是enum从该属性文件生成一个.或者,使用词典(地图)访问您的属性,例如:
equipment.get("height");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25476 次 |
| 最近记录: |