【问题标题】:Scala Parse String Class and Compile in Run-TimeScala 解析字符串类并在运行时编译
【发布时间】:2016-11-10 20:30:36
【问题描述】:

我想在 scala 中实现一个函数,它可以解析源代码的字符串(类对象)并在运行时将其编译为对象。

例如,该功能是我迄今为止尝试过的。我的目标是在运行时环境中编译运行它,我可以使用它的构造函数或它的函数。此代码有运行时错误,但我不明白如何修复反射类错误。谢谢!

object test {
        def main(args: Array[String]): Unit = {
            val m = universe.runtimeMirror(getClass.getClassLoader)
            val tb = m.mkToolBox()
            val clazz = tb.compile(tb.parse("class insideclass {\n    val model_field = 5\n   def insideclass(model: Int) = {\n        val model_field = model \n    } \n\n    def test() : Int = {\n        model_field\n    }\n\n}\nscala.reflect.classTag[insideclass].runtimeClass"))().asInstanceOf[Class[_]]
            val classinside = universe.typeOf[Class[_]].typeSymbol.asClass
            val ctor = universe.typeOf[Class[_]].declaration(universe.nme.CONSTRUCTOR).asMethod
            val cm=m.reflectClass(classinside)
            val ctorm=cm.reflectConstructor(ctor)
            println(ctorm(10).test())
        }
    }

【问题讨论】:

    标签: scala


    【解决方案1】:

    问题是外部编译器不知道“insideclass”作为类定义存在。一种解决方案是让内部类扩展一些内部和外部编译器都知道的其他类,例如 Function[Int, Int]。在这种情况下,您需要将“测试”方法重命名为“应用”。

    val clazz = tb.compile(tb.parse("class PersonData(x:Int) extends  Function[Int, Int] {\n val allen = x.toInt\n\n override def apply(x:Int):Int = allen}\n scala.reflect.classTag[PersonData].runtimeClass"))().asInstanceOf[Class[_]]
    
    val ctor = clazz.getDeclaredConstructors()(0)
    
    val instance = ctor.newInstance(new Integer(1))
    // this cast can succeed because the outside knows what is Function[Int, Int]
    println(instance.asInstanceOf[Function[Int, Int]].apply(1))
    

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 2013-11-26
      • 2011-08-06
      • 2012-07-21
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2011-10-23
      • 2019-11-17
      相关资源
      最近更新 更多