Quick Start with Nashorn engine

As a replacement, Nashorn succeeded Rhino engine in JDK8 to provide performant JavaScript reflection. There are many real world products built in Java which have scripting portals for users to customize the system, e.g. ServiceNow (although it still uses Rhino by the time this article is written).
Before jumping into Java code, I just want make a very short intro to command line execution using jjs. Simply start bin/jjs.exe by typing jjs in command line after you got system path parameter set up.

$ jjs
jjs> exit()

Start JavaScript engine in Java

To evaluate JavaScript in Java, javax.script.ScriptEngine is used:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript"); // Using default JS engine, i.e. Nashorn
engine.eval("print('hello world!');"); // JS code is essentially a String in Java

Invoke JavaScript Functions from Java

Each ScriptEngine has its own namespace. (In JavaScript point of view, each ScriptEngine hosts one global scope.) Functions within it can run by normal JavaScript calls, as well as Java invocation:

engine.eval("function fun (name) {return 'hello ' + name;}; print(fun('Jianzhao'));");
Invocable invocable = (Invocable) engine;
Object result = invocable.invokeFunction("fun", "William");
System.out.println(result + " : " + result.getClass());

Invoke Java Method from JavaScript

To successfully invoke any Java method, you need a full class name including package path, and should not violating Java security constraint:

package ca.ljz;

import javax.script.*;

public class Cls {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        engine.eval("var Cls = Java.type('ca.ljz.Cls'); print(new Cls().meth('Will'));");
    }
    public String meth(String name) {
        return "hello "+ name;
    }
}

This blog may not be up to date. Please see the original post from Blogger http://ift.tt/2pKWy0p
via IFTTT.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s