Javaエンジン

2485 ワード

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;

import javax.print.DocFlavor.URL;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;


@SuppressWarnings("all")  //       
public class Engine_GetRhino {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//      
		ScriptEngineManager sem = new ScriptEngineManager();
		ScriptEngine engine=sem.getEngineByName("javascript");
		
		//    ,         
		engine.put("msg", "you are very good");
		
		String str = "var user = {name:'waibizi',age:18,schools:['    ','     ']};";
		str += "print(user.name);";
		
		
		
		//    
		try {
			engine.eval(str);
			engine.eval("msg='you are very bad';");
		} catch (ScriptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//    
		System.out.println(engine.get("msg"));
		
		
		
		try {
			//    
			engine.eval("function add(a,b){var sum = a + b; return sum;}");
			engine.eval("function add1(){var sum = 123 + 321; return sum;}");
			//    
			Invocable jsInvoke = (Invocable) engine;
			Object result=jsInvoke.invokeFunction("add", new Object[] {15,13});  //      
			Object result1=jsInvoke.invokeFunction("add1");  //      
			System.out.println(result);
			System.out.println(result1);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		try {
			//js  java  ,  java  
			
//			         JDK1.6 ,      ,       
//			String jsCode = "importPackage(java.util); var list=Arrays.asList([\"    \",\"     \",\"    \"]);"; 
			
			String jsCode = "var list=java.util.Arrays.asList([\"    \",\"     \",\"    \"]);";
			engine.eval(jsCode);
			List list = (List) engine.get("list");
			for(int i=0;i 
 

 
 
 a.jsは以下の通り
 
function test(){
	var a=666;
	print("invoke js file:"+a);
}

test();