java 8 New JavaScript Engine

Java 8增加了许多新特性,其中个人认为最主要,最有趣的两个特性就是Lambda表达式和javaScript引擎的支持,这篇博客就记录测试js引擎的过程.

package lebronyouxiao.java.Test;

import java.io.FileNotFoundException;
import java.io.FileReader;

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

/**
 * this class is used to test the javaScript support of java 8
 * @author you
 * @see ScriptEngine
 */
public class ScriptEngineTest {


	private static final String JsFile = "/Users/lebronyouxiao/Documents/workspace/MyFrame/src/test.js";
	
	
	public static void main(String[] args){
		
		try {
			ScriptEngine engine = ScriptUtil.execuetScipt(new FileReader(JsFile));
			
			System.out.println(engine.eval("sum(1,2)"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ScriptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	/**
	 * this inner class is used to get the Script Engine by diffrent way
	 * @author you
	 *
	 */
	static class ScriptUtil{
		
		
		public static ScriptEngine executeScipt(String function) throws ScriptException{
			ScriptEngineManager engineManager = new ScriptEngineManager();
			ScriptEngine engine = engineManager.getEngineByName("nashorn");
			engine.eval(function);
			return engine;
		}
		
		public static ScriptEngine execuetScipt(FileReader file) throws ScriptException{
			ScriptEngineManager engineManager = new ScriptEngineManager();
			ScriptEngine engine = engineManager.getEngineByName("nashorn");
			engine.eval(file);
			return engine;
		}
	}
}

/**
 * this a javaScript file for test the Nashorn java script
 *engine in java
 */

function sum(a,b){
	return a+b;
}

var LinkedList = Java.type("java.util.LinkedList");
var ArraysOfInt = Java.type("int[]");
var printer =  java.lang.System.out;


var list = new LinkedList;
list.add(1);
list.add(2);
print(list);

var array = new ArraysOfInt(3);
printer.println("the length of array is : "+array.length);

    原文作者:lebronyouxiao
    原文地址: https://blog.csdn.net/youlebron/article/details/22242801
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞