[英]Using Scala Toolbox is it possible to define a case class and use it later into eval code?
I would like to give the case class definition to the Toolbox and be able to use them later when I do the eval.我想将案例 class 定义提供给工具箱,以便稍后在进行评估时使用它们。 The Toolbox should be able to know the definitions of the case classes.工具箱应该能够知道案例类的定义。
For example, I am able to define a case class named Authentication with args email例如,我可以使用 args email 定义一个名为 Authentication 的案例 class
import scala.reflect.runtime._
import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox
val cm = universe.runtimeMirror(getClass.getClassLoader)
val toolBox = cm.mkToolBox()
val myClass: ClassDef = q"case class Authentication(email: String)".asInstanceOf[ClassDef]
val definedClass = toolBox.define(myClass)
println(definedClass)
It prints class Authentication
Then I would like to recall it into my Eval expression and match it它打印class Authentication
然后我想将它召回到我的 Eval 表达式中并匹配它
val myCode =
q""" def myFunction(x:Any){
x match{
case Authentication(param) => println("Auth received!")
}
}"""
toolBox.eval(myCode)
But it tells me, Authentication was not found.但它告诉我,找不到身份验证。 Any idea of how to accomplish it?知道如何完成它吗?
Since .apply
and .unapply
are methods of companion object, you missed .companion
similarly to Scala reflection: how do I define a case class at runtime and then reference to it?由于.apply
和.unapply
是伴随 object 的方法,因此您错过了.companion
类似的.companion 反射:如何在运行时定义案例 class 并引用它
Try尝试
val myCode =
q"""
def myFunction(x: Any) = {
x match{
case ${definedClass.companion}(param) => println("Auth received!")
}
}
myFunction(${definedClass.companion}("111@aaa"))
"""
toolBox.eval(myCode) // toolBox.eval(myCode)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.