scala 作为脚本语言 [英] scala as scripting language

查看:19
本文介绍了scala 作为脚本语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
“eval”在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆