How to load .js files into a Rhino context in Java

≡放荡痞女 提交于 2019-11-30 09:05:46

Are you aware that Rhino ships in Java 6?

String javaScriptExpression = "sayHello(name);";
Reader javaScriptFile = new StringReader(
    "function sayHello(name) {\n"
        + "    println('Hello, '+name+'!');\n" + "}");

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory
    .getEngineByName("JavaScript");
ScriptContext context = engine.getContext();
context.setAttribute("name", "JavaScript",
    ScriptContext.ENGINE_SCOPE);

engine.eval(javaScriptFile);
engine.eval(javaScriptExpression);

If you want to use it with Java 5, you'll have to download the API separately. You can get engines for many popular scripting languages from scripting.dev.java.net.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!