论坛首页 Java企业应用论坛

Java执行javascript

浏览 1478 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (1) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-08-06  
package com.byd.mes.util.script;

import java.util.HashMap;
import java.util.Map;

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

import sun.org.mozilla.javascript.internal.NativeObject;

public class ScriptUtils {
	private static final ScriptEngineManager manager = new ScriptEngineManager();
	private Map<String,Callback> custom = new HashMap<String,Callback>();
	
	public interface Callback{
		void callBack(String script);
	}
	
	private Map<String,Callback> conf = new HashMap<String,Callback>();
	{
		conf.put("testing", new ScriptUtils.Callback(){
			@Override
			public void callBack(String script) {
				ScriptEngine engine = manager.getEngineByName("javascript");
				try {
					engine.eval(script);
					Invocable invocableEngine = (Invocable)engine;
					NativeObject obj = (NativeObject) invocableEngine.invokeFunction("testing", 1);			
					System.out.println(obj.get("nextOperation", null));
				} catch (Exception e) {
					throw new RuntimeException("执行Script脚本失败[function:testing]",e);
				}
				
			}});
	}
	
	public static void testing(String script){
		
	}

	public void setCustom(Map<String,Callback> custom) {
		this.custom = custom;
		this.conf.putAll(custom);
	}

	public Map<String,Callback> getCustom() {
		return custom;
	}
}

 

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics