如何在Scala中将类放入JJS ScriptEngine的范围内

时间:2014-05-08 13:29:08

标签: java scala nashorn

我在scala中运行Class时未能ScriptEngine进入nashorn的范围。

这是我尝试做的事情:

import javax.script.{ScriptEngine, ScriptEngineManager}
case class MyClass(id: Option[String], name: Option[String])

val manager: ScriptEngineManager = new ScriptEngineManager

val engine: ScriptEngine = manager.getEngineByName("nashorn")

var simpleScript: String = 
         """
         var myClass = new MyClass('myId', 'myName'); print(myClass.id);
         """`

engine.eval(simpleScript)

是否有人知道如何从MyClass启动JavaScript

我得到以下例外:

javax.script.ScriptException: ReferenceError: "MyClass" is not defined in <eval> at line number 1`

1 个答案:

答案 0 :(得分:2)

我认为它与尝试访问java类是一样的,值得一试

http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/javascript.html#A1147187建议

var MyClass = Java.type("MyClass");
var inst = new MyClass("myId", "myName");