在运行时以字符串形式编译 Scala 源代码
Compiling Scala source in a string at runtime
我的程序中有一个摘要 class
abstract class Deployment {
/**
* Defines a logger to be used by the deployment script
*/
protected val logger = LoggerFactory.getLogger(this.getClass)
/**
* Defines the entry point to the deployment
*
* @throws java.lang.Exception Thrown on the event of an unrecoverable error
*/
def run(): Unit
}
当我尝试加载 classes 时,它们处于源代码形式,所以我在加载时编译它们,就像这样
val scriptFile = new File("testing.scala")
val mirror = universe.runtimeMirror(getClass.getClassLoader)
val toolBox = mirror.mkToolBox()
val parsedScript = toolBox.parse(Source.fromURI(scriptFile.toURI).mkString)
val compiledScript = toolBox.eval(parsedScript)
val deployment = compiledScript.asInstanceOf[Deployment]
deployment.run()
这是测试文件
import au.com.cleanstream.kumo.deploy.Deployment
class testing extends Deployment {
override def run(): Unit = {
logger.info("TEST")
}
}
但是当我 运行 我得到 java.lang.AssertionError: assertion failed
的代码时,我也很累 toolBox.compile(parsedScript)
但得到了同样的东西。
非常感谢任何帮助!
toolBox.eval(parsedScript)
returns () => Any
在您的情况下,测试文件 returns Unit
和 compiledScript
的类型为 BoxedUnit
.
如果您将测试文件更改为 return 某个值,您将能够访问它。
我修改了测试文件如下:
object Testing extends Deployment {
override def run(): Unit = {
logger.info("TEST")
}
}
Testing //This is the SOLUTION
我的程序中有一个摘要 class
abstract class Deployment {
/**
* Defines a logger to be used by the deployment script
*/
protected val logger = LoggerFactory.getLogger(this.getClass)
/**
* Defines the entry point to the deployment
*
* @throws java.lang.Exception Thrown on the event of an unrecoverable error
*/
def run(): Unit
}
当我尝试加载 classes 时,它们处于源代码形式,所以我在加载时编译它们,就像这样
val scriptFile = new File("testing.scala")
val mirror = universe.runtimeMirror(getClass.getClassLoader)
val toolBox = mirror.mkToolBox()
val parsedScript = toolBox.parse(Source.fromURI(scriptFile.toURI).mkString)
val compiledScript = toolBox.eval(parsedScript)
val deployment = compiledScript.asInstanceOf[Deployment]
deployment.run()
这是测试文件
import au.com.cleanstream.kumo.deploy.Deployment
class testing extends Deployment {
override def run(): Unit = {
logger.info("TEST")
}
}
但是当我 运行 我得到 java.lang.AssertionError: assertion failed
的代码时,我也很累 toolBox.compile(parsedScript)
但得到了同样的东西。
非常感谢任何帮助!
toolBox.eval(parsedScript)
returns () => Any
在您的情况下,测试文件 returns Unit
和 compiledScript
的类型为 BoxedUnit
.
如果您将测试文件更改为 return 某个值,您将能够访问它。 我修改了测试文件如下:
object Testing extends Deployment {
override def run(): Unit = {
logger.info("TEST")
}
}
Testing //This is the SOLUTION