Scala作为脚本语言 [英] scala as scripting language
本文介绍了Scala作为脚本语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
评估在Scala中
我知道scala是一种编译语言,但我也知道我可以将类动态加载到jvm中,并且可以在运行时调用scala编译器,最后但同样重要的一点是,我确实有一个很棒的repl,因此应该可以将scala作为脚本语言。
I know scala is a compiled language, but I do also know that I can dynamically load classes into the jvm, and I can call the scala compiler at runtime, last but not least I do also have an awesome repl, so having scala as a scripting language should be possible.
所以我需要执行一些任务:
so there are some tasks I need to get to run:
简单的解释:
val src = """ println("Hello World") """
interpret(src)
调用外部函数:
object A{
def foo =
println("Hello World")
}
val src = """ A.foo """
interpret(src)
实现功能:
trait T{
def foo:String
}
val src = """ class A extends T{ def foo = "Hello World" } """
interpret(src)
val t = loadClassAndCreatInstance.asInstanceOf[T]
println(t.foo)
获得解决方案会很棒解决我所有的问题。
it would be great to get a solution to all my problems.
推荐答案
我已经找到了如何使用scala作为脚本语言,但是我仍然遇到问题classLoader
somehow I already found out how to use scala as scripting language but I still have a problem with the classLoader
object O{
def foo = println("Hello World in object O")
}
trait T{
def foo:String
}
object MyInterpreter extends App{
val srcA =
"""
println("Hello World from srcA")
"""
val srcB = """ O.foo """
val srcC = """
class A extends T{
def foo = "Hello World from srcC"
override def toString = "this is A in a src"
}
"""
val out = System.out
val flusher = new java.io.PrintWriter(out)
val interpreter = {
val settings = new import scala.tools.nsc.GenericRunnerSettings( println _ )
new scala.tools.nsc.interpreter.IMain(settings, flusher)
}
interpreter.interpret(srcA)
interpreter.interpret(srcB)
interpreter.compileString(srcC)
val classA = interpreter.classLoader.findClass("A")
println(classA)
val constructors = classA.getDeclaredConstructors
val myinstance = constructors(0).newInstance()
println(myinstance)
//this still throws an classCastException
myinstance.asInstanceOf[T].foo
//but everything else works
}
这篇关于Scala作为脚本语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文