在运行时以字符串形式编译Scala源代码
我的程序中有一个抽象类在运行时以字符串形式编译Scala源代码,scala,reflection,runtime,Scala,Reflection,Runtime,我的程序中有一个抽象类 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 jav
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
}
当我尝试加载类时,它们是源代码形式的,所以我像这样在加载时编译它们
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失败了
,我也厌倦了toolBox.compile(parsedScript)
,但得到了同样的结果
非常感谢您的帮助 toolBox.eval(parsedScript)
返回()=>任何
在您的情况下,测试文件返回Unit
,并且compiledScript
的类型为BoxedUnit
如果您更改测试文件以返回一些值,您将能够访问它。
我对测试文件进行了如下修改:
object Testing extends Deployment {
override def run(): Unit = {
logger.info("TEST")
}
}
Testing //This is the SOLUTION
非常感谢,回顾这一点,它更有意义!是的,更有意义!我想补充一点,这里可以使用匿名对象,
newdeployment{overridedefrun():Unit={logger.info(“TEST”)}//end