1

I am using Java 8 Nashorn to execute a specific previously agreeed upon method. I could Invoke the specific method no problem. One thing that bugged me though is that when I load the script, it also executes it.

For example if file.js contains a print("hello world!") the scriptEngine.eval(new FileReader("./file.js") would execute and print hello world. I have to do this before I could invoke the specific method I want.

Is there a way to eval()/load the scripts without executing it?

Thanks

2
  • "Is there a way to load the scripts without executing it?" What would be the result of this operation? Do you just want to get the source text? In that case, just read the file with FileReader? Commented Mar 17, 2016 at 22:56
  • I wanted to eventually Invoke a specific method, but I am unable to do that without previously calling .eval() which executes the script :( Commented Mar 17, 2016 at 23:08

1 Answer 1

2

turns out You could do this by Casting engine to Compilable then call the compile function.

final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
final Compilable compilable = (Compilable) engine;
        final Invocable invocable = (Invocable) engine;
        final String statement = "function fetch(values) { return values['first_name'] + ' ' + values['last_name']; };";
        final CompiledScript compiled = compilable.compile(statement);

This achieved what I want without needing to eval() it

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.