java 执行js

java 执行js

package test;

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

public class Hello{
	

	public static void main(String[] args) throws NoSuchMethodException {
		
		ScriptEngineManager sem = new ScriptEngineManager(); 
		 ScriptEngine se = sem.getEngineByName("js");  
		 try {
			 String script = "function check(){ return JSON.stringify(arguments);};"; 
			 
			  se.eval(script);  
			  Invocable inv2 = (Invocable) se;  
			  String res=(String)inv2.invokeFunction("check", new String[] {"1", "2"});  
			  System.out.println(res); 
		 } catch (ScriptException ex) { 
			ex.printStackTrace(); 
		 }
		
		
		
	}
}