简体   繁体   English

使用 Scala 工具箱是否可以定义一个案例 class 并稍后将其用于评估代码?

[英]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.

相关问题 Scala 反射:如何在运行时定义一个案例 class 然后引用它? - Scala reflection: how do I define a case class at runtime and then reference to it? 是否可以为现有的Java bean类获取Scala案例类? - Is it possible to get a Scala case class for an exisiting Java bean class? 使用 Jackson 对 Scala 案例类进行(反)序列化 - Using Jackson to (De)-serialize a Scala Case Class 是否可以在 Java 中定义一个变量并在 JSP 代码中使用它? - Is it possible to define a variable in Java and use that in JSP code? scala案例类复制方法是从java代码中看不到的 - scala case class copy method is unseen from java code 如何使用fasterxml.jackson验证scala中的嵌套案例类 - how to use fasterxml.jackson to validate nested case class in scala 是否可以将Java方法类用作Scala Function {0-22}类 - Is it possible to use Java Method class as Scala Function{0-22} class 稍后在Java代码中定义实例通用类型 - Define instance generic type later on in code in Java 在Scala的case类和类字段中使用Optional是否有代码味道? - Is using Optional in Scala's case classes and classes fields a code smell? 是否可以#define Java中的类? - Is it possible to #define a class in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM