下面是我通常在 groovy 中使用的一个小示例,但我想要在 java 中使用类似的东西。
配置文件
datastore{
oracle{
host="localhost"
port=1521
dbname="orcl"
}
db2{
host="localhost"
port=12807
dbname="sppd"
}
}
绝妙的
public class Configuration {
public static final def cfg = new ConfigSlurper().parse(new File("configuration").toURL())
static main(args) {
println cfg.datastore.oracle.host
println cfg.datastore.db2.host
}
}
最佳答案
我猜您想通过属性的完整路径访问该属性,例如来自 Java 的 datastore.oracle.host
就像在 Groovy 中一样。如果是这样,请执行以下操作:
ConfigObject config = new ConfigSlurper().parse(new File("configuration").toURL());
Map flattenedConfig = config.flatten();
String oracleHost = (String) flattenedConfig.get("datastore.oracle.host");
比 Java 属性更好,因为类型得到了维护。来自Groovy User list post .
关于java - java中是否有groovy的ConfigSlurper的等效类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25118732/