java执行js脚本_java执行JavaScript脚本

看到一个帖子说如何执行 字符串表达式,上网查了一下,可以使用JavaScript 中的eval表达式来执行;自JDK 6开始增加了对脚本语言的支持;

Scripting API是用于在Java里面编写脚本语言程序的API, 在Javax.script中可以找到Scripting API,我们就是用这个API来编写JavaScript程序,这个包里面有一个ScriptEngineManager类,它是使用Scripting API的入口,ScriptEngineManager可以通过jar服务发现(service discovery)机制寻找合适的脚本引擎类(ScriptEngine),使用Scripting API的最简单方式只需下面三步

1、创建一个ScriptEngineManager对象

2、通过ScriptEngineManager获得ScriptEngine对象

3、用ScriptEngine的eval方法执行脚本

import java.util.ArrayList;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.Map.Entry;

import javax.script.Invocable;

import javax.script.ScriptEngine;

import javax.script.ScriptEngineManager;

import javax.script.ScriptException;

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

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

public class Tests {

public static void main(String[] args) throws Exception {

ScriptEngineManager factory = new ScriptEngineManager();

ScriptEngine engine = factory.getEngineByName("JavaScript");

engine.eval("print('hello')");

// testScriptVariables(engine);// 演示如何暴露Java对象为脚本语言的全局变量

// testInvokeScriptMethod(engine);// 演示如何在Java中调用脚本语言的方法

// testScriptInterface(engine);// 演示脚本语言如何实现Java的接口

// testUsingJDKClasses(engine);// 演示脚本语言如何使用JDK平台下的类

// test(engine);

}

/**

* 将java变量变位JS变量.

*

* @param engine

* @throws ScriptException

*/

public static void testScriptVariables(ScriptEngine engine) throws ScriptException {

Map map = new HashMap();

map.put("a", "将java参数 变为脚本变量");

engine.put("map", map);

engine.eval(" map.put('b',new Date()); println(map.get('a') +'  '+ map.get('b'));");

}

/**

* 执行JS函数,运算字符串公式.

*

* @param engine

* @throws Exception

*/

public static void testInvokeScriptMethod(ScriptEngine engine) throws Exception {

String script = "function calc(num1,num2) { return (num1+num2)/2;}  function test(){return 12*6-9/2 +5;}";

engine.eval(script);

Invocable inv = (Invocable) engine;

Double res = (Double) inv.invokeFunction("test");

System.out.println("res:" + res);

}

/**

* JS实现java接口.

*

* @param engine

* @throws ScriptException

*/

public static void testScriptInterface(ScriptEngine engine) throws ScriptException {

String script = "var obj = new Object();obj.run = function() { println('run method called');}";

engine.eval(script);

Object obj = engine.get("obj");

Invocable inv = (Invocable) engine;

Runnable r = inv.getInterface(obj, Runnable.class);

Thread th = new Thread(r);

th.start();

}

/**

* js 使用java类.

*

* @param engine

* @throws Exception

*/

public static void testUsingJDKClasses(ScriptEngine engine) throws Exception {

// Packages是脚本语言里的一个全局变量,专用于访问JDK的package

String js = "function doSwing(t){var f=new Packages.javax.swing.JFrame(t);f.setSize(400,300);f.setVisible(true);}";

// String js =

// "function doSwing(t){var f=Packages.java.util.UUID.randomUUID();print(f)}";

engine.eval(js);

Invocable inv = (Invocable) engine;

inv.invokeFunction("doSwing", "Scripting Swing");

}

/**

* 将前台传过来的json数组构造成java的List>,然后就可以随心所欲的使用该list了

* 当然可以使用第三方jar采用json to bean的方式,而且这种方案更优雅,但是需要引入第三方库

*

* @throws NoSuchMethodException

* @throws ScriptException

*/

public static void test(ScriptEngine engine) throws ScriptException, NoSuchMethodException {

// String json =

// "{'key1':'a','son':{'dd':'dd','a':8},'ran':Math.random()},{'key3':'xor'}";

String json = "{'key1':'a','son':[{'dd':'dd'},{'dd1':'dd1'}],'ran':Math.random()},{'key3':'xor'}";

NativeArray json2array = json2array(engine, "[" + json + "]");

List> list = array2list(engine, json2array);

System.out.println(list);

}

public static NativeArray json2array(ScriptEngine engine, String json) throws ScriptException, NoSuchMethodException {

String script = "function hello() { return " + json + ";}";

engine.eval(script);

Invocable inv = (Invocable) engine;

Object obj = inv.invokeFunction("hello");

return (NativeArray) obj;

}

public static List> array2list(ScriptEngine engine, NativeArray nativeArray) throws ScriptException, NoSuchMethodException {

List> list = new ArrayList>();

engine.put("list", list);

engine.put("arr", nativeArray);

StringBuffer sb = new StringBuffer("function dosomething(){      ");

sb.append(" for (n=0; n< arr.length; n++){  ");

sb.append("     var map=new Packages.java.util.HashMap();  ");

sb.append("     for (i in arr[n]){ map.put(i,arr[n][i]);");

sb.append("  }     list.add(map);     }  }  ");

engine.eval(sb.toString());

Invocable inv = (Invocable) engine;

inv.invokeFunction("dosomething");

for (Map map : list) {

Set> entrySet = map.entrySet();

for (Entry entry : entrySet) {

Object object = entry.getValue();

if (object instanceof NativeArray) {

map.put(entry.getKey(), array2list(engine, (NativeArray) object));

} else if (object instanceof NativeObject) {

map.put(entry.getKey(), obj2map(engine, (NativeObject) object));

}

}

}

return list;

}

public static Map obj2map(ScriptEngine engine, Object nativeObject) throws ScriptException, NoSuchMethodException {

Map map = new HashMap();

engine.put("map", map);

engine.put("obj", nativeObject);

String script = " function dosomething(){ for (i in obj){  map.put(i,obj[i]);  } }";

engine.eval(script);

Invocable inv = (Invocable) engine;

inv.invokeFunction("dosomething");

return map;

}

}

参考:http://relive123-yahoo-com-cn.iteye.com/blog/784700

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值