【发布时间】:2016-08-25 05:16:14
【问题描述】:
我有以下代码可在 Scala 2.10 中运行,以便在 Scala 中运行时编译外部类
/**
* Compile scala files and keep them loaded in memory
* @param classDir Directory storing the generated scala files
* @throws IOException if there is problem reading the source files
* @return Classloader that contains the compiled external classes
*/
@throws[IOException]
def compileFiles(classDir: String): AbstractFileClassLoader = {
val files = recursiveListFiles(new File(classDir))
.filter(_.getName.endsWith("scala"))
println("Loaded files: \n" + files.mkString("[", ",\n", "]"))
val settings: GenericRunnerSettings = new GenericRunnerSettings(err => println("Interpretor error: " + err))
settings.usejavacp.value = true
val interpreter: IMain = new IMain(settings)
files.foreach(f => {
interpreter.compileSources(new BatchSourceFile(AbstractFile.getFile(f)))
})
interpreter.getInterpreterClassLoader()
}
然后在其他地方,我可以使用类加载器引用来实例化类,例如
val personClass = classLoader.findClass("com.example.dynacsv.PersonData")
val ctor = personClass.getDeclaredConstructors()(0)
val instance = ctor.newInstance("Mr", "John", "Doe", 25: java.lang.Integer, 165: java.lang.Integer, 1: java.lang.Integer)
println("Instantiated class: " + instance.getClass.getCanonicalName)
println(instance.toString)
然而,上述方法不再有效,因为 getInterpreterClassLoader 方法已从 scala.tools.nsc.interpreter.IMain 中删除。此外,AbstractFileClassLoader 已被移动和弃用。不再允许从外部包调用类加载器中的findClass方法。
在 Scala 2.11 中执行上述操作的推荐方法是什么?谢谢!
【问题讨论】:
标签: scala scala-2.11