有没有办法在.properties文件中包含条件语句?
喜欢:
if(condition1)
xyz = abc
else if(condition2)
xyz = efg
Run Code Online (Sandbox Code Playgroud)
否在属性文件中没有这样的条件语句,可能你会写一个包装器Properties来封装你的逻辑
例:
class MyProperties extends Properties {
/**
*
*
*
* @param key
* @param conditionalMap
* @return
*/
public String getProperty(String key, List<Decision> decisionList) {
if (decisionList == null) {
return getProperty(key);
}
Long value = Long.parseLong(getProperty(key));
for (Decision decision : decisionList) {
if (Condition.EQUALS == decision.getCondition() && decision.getValue().equals(value)) {
return getProperty(decision.getTargetKey());
}
}
return super.getProperty(key);
}
}
Run Code Online (Sandbox Code Playgroud)
和
enum Condition {
EQUALS, GREATER, LESSER
}
Run Code Online (Sandbox Code Playgroud)
和
class Decision {
Condition condition;
String targetKey;
Long value;
//accessor
public Condition getCondition() {
return condition;
}
public void setCondition(Condition condition) {
this.condition = condition;
}
public String getTargetKey() {
return targetKey;
}
public void setTargetKey(String targetKey) {
this.targetKey = targetKey;
}
}
Run Code Online (Sandbox Code Playgroud)
所以现在例如,如果要读取属性文件,请获取年龄类别,如果它大于0且小于10读取 kid
也许你可以通过这些条件清单,
注意:这个设计可以进行很多改进(不是很好的设计),它只是为了说明如何包装属性和添加OP想要的东西
不,这是不可能的.文件格式免费提供:http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#load%28java.io.Reader%29.
在Java代码中执行此操作:
if (condition1) {
return properties.getProperty("xyz.1");
}
else if (condition2) {
return properties.getProperty("xyz.2");
}
Run Code Online (Sandbox Code Playgroud)