新特性7-Nashorn JavaScript引擎

Java 8提供了新的Nashorn JavaScript引擎,使得我们可以在JVM上开发和运行JS应用。Nashorn JavaScript引擎是javax.script.ScriptEngine的另一个实现版本,这类Script引擎遵循相同的规则,允许Java和JavaScript交互使用,例子代码如下:

package com.ehking.example.java8.newfeature.demo07;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * Created by shiyanwu on 2017/4/17.
 * java测试 Nashorn JavaScript
 */
public class Java8JavaScript {

    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        System.out.println(engine.getClass().getName());
        try {
            System.out.println("output: " + engine.eval("function show() {return 10;}; show();"));
        } catch (ScriptException e) {
            e.printStackTrace();
        }

        // jdk.nashorn.api.scripting.NashornScriptEngine
        // output: 10
    }
}

你可能感兴趣的:(新特性7-Nashorn JavaScript引擎)