admin管理员组

文章数量:1334183

I have the following code which works:

ScriptEngine jsEngine = ScriptEngineManager.new().getEngineByName("nashorn");
jsEngine.eval("some script");

jsEngine.invokeMethod(jsEngine.eval("foo"), "bar");

but I want to do use a pre-piled script so I don't have to evaluate the script every time I need to run it, so I'm trying;

ScriptEngine jsEngine = ScriptEngineManager.new().getEngineByName("nashorn");
CompiledScript piledJS = jsEnginepile("some script");

but then I'm not sure what to do with CompiledScript, how do I invoke a method? it doesn't implement anything else than eval() apparently: .html

I have the following code which works:

ScriptEngine jsEngine = ScriptEngineManager.new().getEngineByName("nashorn");
jsEngine.eval("some script");

jsEngine.invokeMethod(jsEngine.eval("foo"), "bar");

but I want to do use a pre-piled script so I don't have to evaluate the script every time I need to run it, so I'm trying;

ScriptEngine jsEngine = ScriptEngineManager.new().getEngineByName("nashorn");
CompiledScript piledJS = jsEngine.pile("some script");

but then I'm not sure what to do with CompiledScript, how do I invoke a method? it doesn't implement anything else than eval() apparently: https://docs.oracle./javase/8/docs/api/javax/script/CompiledScript.html

Share Improve this question asked Aug 27, 2015 at 14:15 Pablo FernandezPablo Fernandez 288k139 gold badges403 silver badges642 bronze badges 1
  • I think my approach here might be wrong, so I wrote a more basic question: stackoverflow./questions/32252843/… – Pablo Fernandez Commented Aug 27, 2015 at 14:58
Add a ment  | 

1 Answer 1

Reset to default 5

You call the method?

Here are few examples: http://www.programcreek./java-api-examples/index.php?api=javax.script.CompiledScript


Example:

import java.util.*;
import javax.script.*;

public class TestBindings {
    public static void main(String args[]) throws Exception {
        String script = "function doSomething() {var d = date}";
        ScriptEngine engine =  new ScriptEngineManager().getEngineByName("JavaScript");
        Compilable pilingEngine = (Compilable) engine;
        CompiledScript cscript = pilingEngine.pile(script);

        //Bindings bindings = cscript.getEngine().createBindings();
        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        for(Map.Entry me : bindings.entrySet()) {
            System.out.printf("%s: %s\n",me.getKey(),String.valueOf(me.getValue()));
        }
        bindings.put("date", new Date());
        //cscript.eval();
        cscript.eval(bindings);

        Invocable invocable = (Invocable) cscript.getEngine();
        invocable.invokeFunction("doSomething");
    }
}

本文标签: javascriptHow do you invoke a method in a Nashorn CompiledScriptStack Overflow