码迷,mamicode.com
首页 > 编程语言 > 详细

JDK8在Java转让Javascript脚本引擎动态地定义和运行代码

时间:2015-07-18 19:56:32      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

import java.lang.*;
import java.util.Arrays;
import java.util.List;

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

public class ScriptEngineTest {

public static void main(String[] args) throws Exception {
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine engine = sem.getEngineByName("javascript");     //python or jython, 

<pre name="code" class="html">   //向上下文中存入变量
   engine.put("msg", "just a test");
   //定义类user
   String str = "msg += '!!!';var user = {name:'tom',age:23,hobbies:['football','basketball']}; ";
   engine.eval(str);

   //从上下文引擎中取值
   String msg = (String) engine.get("msg");
   String name = (String) engine.get("name");
   String[] hb = engine.get("hb");
   System.out.println(msg);
   System.out.println(name + ":" + hb[0]);

   //定义数学函数
   engine.eval("function add (a, b) {c = a + b; return c; }");

    //取得调用接口
    Invocable jsInvoke = (Invocable) engine;

  //定义加法函数

  Object result1 = jsInvoke.invokeFunction("add", new Object[] { 10, 5 });

  System.out.println(result1);

  //调用加法函数,注意參数传递的方法

  Adder adder = jsInvoke.getInterface(Adder.class);

  int result2 = adder.add(10, 35);

  System.out.println(result2);

  //定义run()函数

  engine.eval("function run() {print('www.java2s.com');}");

  Invocable invokeEngine = (Invocable) engine;

  Runnable runner = invokeEngine.getInterface(Runnable.class);
  //定义线程执行之

  Thread t = new Thread(runner);

  t.start();

  t.join();

  //导入其它java包

  String jsCode = "importPackage(java.util);

  var list2 = Arrays.asList(['A', 'B', 'C']); ";

  engine.eval(jsCode);

  List<String> list2 = (List<String>) engine.get("list2");

  for (String val : list2) { System.out.println(val);}

  }

}




 脚本引擎为实现动态功能(如插件机制)提供了良好的扩展性.

有关引擎接口的文档:

ScriptEngine

版权声明:本文博客原创文章,博客,未经同意,不得转载。

JDK8在Java转让Javascript脚本引擎动态地定义和运行代码

标签:

原文地址:http://www.cnblogs.com/lcchuguo/p/4657413.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!