我有以下代码在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()
}
Run Code Online (Sandbox Code Playgroud)
然后在其他地方,我可以使用类加载器引用来实例化类,例如
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)
Run Code Online (Sandbox Code Playgroud)
但是,由于getInterpreterClassLoader方法已被删除,上述内容不再有效scala.tools.nsc.interpreter.IMain.此外,AbstractFileClassLoader已被移动和弃用.不再允许findClass从外部包调用类加载器中的方法.
在Scala 2.11中执行上述操作的建议方法是什么?谢谢!
dve*_*eim 18
如果你的目标是在运行时运行外部scala类,我建议使用eval scala.tools.reflect.ToolBox(它包含在REPL中,但是对于正常使用,你必须添加scala-reflect.jar):
import scala.reflect.runtime.universe
import scala.tools.reflect.ToolBox
val tb = universe.runtimeMirror(getClass.getClassLoader).mkToolBox()
tb.eval(tb.parse("""println("hello!")"""))
Run Code Online (Sandbox Code Playgroud)
您也可以使用编译文件tb.compile.
用示例修改:假设您有外部文件
class PersonData() {
val field = 42
}
scala.reflect.classTag[PersonData].runtimeClass
Run Code Online (Sandbox Code Playgroud)
所以你也是
val clazz = tb.compile(tb.parse(src))().asInstanceOf[Class[_]]
val ctor = clazz.getDeclaredConstructors()(0)
val instance = ctor.newInstance()
Run Code Online (Sandbox Code Playgroud)
其他可能性(几乎)是无限的,您可以获得完整的树AST并根据需要使用它:
showRaw(tb.parse(src)) // this is AST of external file sources
// this is quasiquote
val q"""
class $name {
..$stats
}
scala.reflect.classTag[PersonData].runtimeClass
""" = tb.parse(src)
// name: reflect.runtime.universe.TypeName = PersonData
// stats: List[reflect.runtime.universe.Tree] = List(val field = 42)
println(name) // PersonData
Run Code Online (Sandbox Code Playgroud)
有关这些技巧,请参阅官方文档:
http://docs.scala-lang.org/overviews/reflection/symbols-trees-types.html
http://docs.scala-lang.org/overviews/quasiquotes/intro.html
| 归档时间: |
|
| 查看次数: |
4504 次 |
| 最近记录: |