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

后端 未结 1 1089

Here is my situation:

I have access to a Rhino Context object in a Java class. I want to read in a bunch of .js files and pass them along to the Rhino context to ha

1条回答
  •  甜味超标
    2020-12-31 13:40

    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.

    0 讨论(0)
提交回复
热议问题