How do I set up jsr223 scripting with scala as scripting language

泪湿孤枕 提交于 2019-12-04 05:26:47
michid

Have a look at the test cases in the scala/script module of Apache Sling for a working example. The script and its entry point (that is the object) need to follow certain conventions. I'll provide more information on these if required later.

For a general overview of the scripting engine see my session slides from Scala Days 2010.

Update: Scripts must be of the following form:

package my.cool.script {
  class foo(args: fooArgs) {
    import args._ // import the bindings
    println("bar:" + bar)
  }
}

The type of args is generated by the script engine and is named after the simple class name of the script appended with 'Args'. Further the example assumes, that the Bindings passed for script evaluation contains a value for the name 'bar'. For further details see the class comment on ScalaScriptEngine.

You need to pass the name of your script class to the script engine. You do this by putting the fully qualified script name (i.e. my.cool.script.foo) into the ScriptContext by the name 'scala.script.class'.

With the conclusion of https://issues.scala-lang.org/browse/SI-874 in version 2.11, it should be as easy as what is shown in the ticket:

import javax.script.*;
ScriptEngine e = new ScriptEngineManager().getEngineByName("scala");
e.getContext().setAttribute("label", new Integer(4), ScriptContext.ENGINE_SCOPE);
try {
    engine.eval("println(2+label)");
} catch (ScriptException ex) {
    ex.printStackTrace();
}

Unfortunately my comment was unreadable without linebreaks - so...

To be able to run the Codesnippet mentioned I needed to make the following changes. I used Scala 2.11.0-M4

public static void main(String args[]){
  ScriptEngine engine = new ScriptEngineManager().getEngineByName("scala");

  // Set up Scriptenvironment to use the Java classpath
  List nil = Nil$.MODULE$;
  $colon$colon vals = $colon$colon$.MODULE$.apply((String) "true", nil);
  ((IMain)engine).settings().usejavacp().tryToSet(vals);ScriptContext.ENGINE_SCOPE);

  engine.getContext().setAttribute("labelO", new Integer(4), ScriptContext.ENGINE_SCOPE);
  try {
    engine.eval("val label = labelO.asInstanceOf[Integer]\n"+
                "println(\"ergebnis: \" + (2 + label ))");
  } catch (ScriptException ex) {
    ex.printStackTrace();
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!