【发布时间】:2018-07-15 03:10:16
【问题描述】:
有没有办法在编译时基于 TypesafeConfig 对象在特定的类/特征/对象中生成方法?
例如,我有这个:
object Main {
val config: Config = ConfigFactory.parseString(
"""
|object {
| name = "go"
|}
""".stripMargin)
generate(config)
}
而预期的结果是:
object Main {
val config: Config = ConfigFactory.parseString(
"""
|object {
| name = "go"
|}
""".stripMargin)
def method: Unit = {
print("go") /* the string comes from the config above */
}
}
这个想法是能够在宏实现的范围内实例化 Config 对象,并使用它的属性来生成代码,例如(非常感谢 Dmytro Minin 的示例):
object GenerateMacro {
def impl(c: blackbox.Context)(annottees: c.Tree*): c.Tree = {
import c.universe._
confObj = ... /* somehow get the real object based on macro input */
annottees match {
case q"$mods object $tname extends { ..$earlydefns } with ..$parents { $self => ..$body }" :: Nil =>
q"""$mods object $tname extends { ..$earlydefns } with ..$parents { $self =>
..$body
def method: Unit = {
print(s"${confObj.getString("object.name")}") /* use confObj's property to "embed" the value into the method generated */
}
}"""
}
}
}
【问题讨论】:
-
不确定它是否是你要找的,但你可能想看看 pureconfig。
标签: scala scala-macros