java8 新特性 v8 nashorn 引擎(五)

風的王子發表於2015-03-23

簡單的javascript 作為文字輸出

ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        String js;

        js = "var map = Array.prototype.map \n";
        js += "var names = [\"john\", \"jerry\", \"bob\"]\n";
        js += "var a = map.call(names, function(name) { return name.length() })\n";
        js += "print(a)";

        try {
            engine.eval(js);
        } catch (ScriptException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ScriptEngine jse = new ScriptEngineManager().getEngineByName("nashorn");
        try {
            jse.eval("print('Hello DoubleCloud! - inline');");
        } catch (ScriptException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


執行javascript 檔案


ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine jse = scriptEngineManager.getEngineByName("nashorn");
        System.out.println("current dir: " + new File(".").getAbsoluteFile());
        try {
            jse.eval(new FileReader("./src/com/test/zcw/java/script.js"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ScriptException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

js檔案語句:eval("print('Hello DoubleCloud! - inline');")


呼叫javascript 函式

 ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
          ScriptEngine jse = scriptEngineManager.getEngineByName("nashorn");
        
          jse.eval(new FileReader("./src/com/test/zcw/java/script.js"));
        
          Invocable runner = (Invocable) jse;
        
          Object result = runner.invokeFunction("hi", "DoubleCloud! - via javascript function");
          System.out.println(result);
          System.out.println(result.getClass());

函式內容:

var hi = function(name)
{
  return 'Hi ' + name;
}


javascript呼叫java

var hw = Java.type('com.test.zcw.java8.JSNashorn');

var result = hw.sayHi("DoubleCloud - calling Java method in JS.");
print(result);

java

static public String sayHi(String name) {
        return "Hi " + name;
    }

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine jse = scriptEngineManager.getEngineByName("nashorn");
        jse.eval(new FileReader("./src/com/test/zcw/java/java8/script.js"));


相關文章