[英][Scala Toolbox]: Compile a Case Class at run-time and then instantiate it
我正在嘗試使用 Scala 反射工具箱定義一個案例 class 並實例化它。 最好的方法是什么?
目前我做
val codeToCompile = q"""case class Authentication(email:String)"""
val tree = toolbox.parse(codeToCompile)
val classDefinition : ClassDef = tree.asInstanceOf[ClassDef]
val definedClass = toolbox.define(classDefinition)
我想使用案例 class 的構造函數在我將它定義到工具箱后在運行時實例化它,比如
val codeToCompile = q"""val myAuth = Authentication("test@gmail.com")"""
val tree = toolbox.parse(codeToCompile)
val binary = toolbox.compile(tree)()
我收到錯誤:找不到身份驗證...我該怎么做?
首先, s
插值器生成字符串, q
插值器生成樹。 所以要么使用q"..."
而不使用.parse
或使用s"..."
和.parse
。
其次,利用ClassSymbol
definedClass
。
第三, .apply
是一種伴隨對象方法。
第四,在單行q"val x =???"
中定義局部變量沒有多大意義使用工具箱,無論如何以后都很難使用這個TermSymbol
(與ClassSymbol
相反)。
嘗試
val codeToCompile = s"""case class Authentication(email:String)"""
val tree = toolbox.parse(codeToCompile)
val classDefinition : ClassDef = tree.asInstanceOf[ClassDef]
val definedClass = toolbox.define(classDefinition)
val codeToCompile1 = q"""${definedClass.companion}("test@gmail.com")"""
val myAuth = toolbox.eval(codeToCompile1) // Authentication(test@gmail.com)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.