[英]Resolve one Typesafe Config object with other
I want to resolve one Config
object, say config1
with other, say config2
. 我想解析一个
Config
对象,例如config1
,另一个config2
。
The only public API that allows something of the sort is config1.withFallback(config2).resolve()
. 唯一允许某种排序的公共API是
config1.withFallback(config2).resolve()
。 However this adds entries from config2
to config1
which is not something we want. 然而,这增加了条目从
config2
到config1
这不是我们想要的东西。
On some investigation, we found a non-public class named ResolveContext
which provides a method for that. 经过一些调查,我们发现了一个名为
ResolveContext
的非公共类,该类提供了一种方法。 So we are making use of that using reflection. 因此,我们正在通过反射来利用它。 Our current code:
我们当前的代码:
object ConfigImplicits {
implicit class RichConfig(val config: Config) extends AnyVal {
def resolveWith(source: Config): Config = {
val resolver = resolveContext.getDeclaredMethod(
"resolve",
abstractConfigValue,
abstractConfigObject,
configResolveOptions
)
resolver.setAccessible(true)
resolver.invoke(
null,
config.underlyingAbstractConfigObject,
source.underlyingAbstractConfigObject,
ConfigResolveOptions.defaults
).asInstanceOf[ConfigObject].toConfig
}
def underlyingAbstractConfigObject = {
val f = simpleConfig.getDeclaredField("object")
f.setAccessible(true)
f.get(config)
}
}
val resolveContext = Class forName "com.typesafe.config.impl.ResolveContext"
val abstractConfigValue = Class forName "com.typesafe.config.impl.AbstractConfigValue"
val abstractConfigObject = Class forName "com.typesafe.config.impl.AbstractConfigObject"
val configResolveOptions = classOf[ConfigResolveOptions]
val simpleConfig = Class forName "com.typesafe.config.impl.SimpleConfig"
}
We realize that relying on non-public innards might not be a good idea. 我们认识到,依靠非公共内部不是一个好主意。 So:
所以:
There is not AFAIK a public method. 没有AFAIK公共方法。 A less-fragile workaround instead of relying on private API might be to first resolve with your source object in there as a fallback, then iterate over the keys in the source object you resolved from and just remove those unwanted keys from the target object.
一个不那么脆弱的解决方法而不是依赖私有API可能是先解析源对象在其中作为后备,然后迭代所解析的源对象中的键,然后从目标对象中删除那些不需要的键。
I can't think of a reason not to add a Config.resolveWith(), though I wonder if there was a reason since I do remember considering it. 我想不出一个不添加Config.resolveWith()的理由,尽管我想知道是否有原因,因为我确实考虑过。 Maybe I just figured nobody would use it.
也许我只是认为没有人会使用它。
If you do a pull request, be sure to include tests and docs. 如果您提出拉取请求,请确保包括测试和文档。 I think the pull request is reasonable, assuming it turns out to be very little code (as I would expect).
我认为pull请求是合理的,假设它原来是很少的代码(正如我期望的那样)。 The current master branch is open for API additions, to appear in an eventual 1.2 release.
当前的master分支已打开,可以添加API,最终出现在1.2版本中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.