Rhino 实践

1. Rhino是什么

简单的理解,就是一个java版的javascript引擎,它有mozilla开源提供。

JavaScript implemented in Java!

Drop-in alternative to Java 

Not a web-browser environment: no DOM, no CSS

Just one language: no browser inconsistencies!

 

Vs Node.js

Evented I/O for V8 JavaScript

性能?

……

 

2.代码

/**** jdk6自带,首先初始化 js引擎 ***/
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");


/**** 1.调用hello对象方法 ***/
HelloWorld hello = new HelloWorld();
engine.put("script_hello", hello);
String script1 = "script_hello.sayHello();";
engine.eval(script1);  

/**** 2.脚本中创建和使用java对象 ***/
String script2 = "var file = java.io.File('/tmp/script_test');var path = file.getPath();print('File path=='+path+'\\r\\n');";
engine.eval(script2);

 

/**** 使用Rhino.jar ***/
Context cx = Context.enter();
String str = "9*(1+2)";
Scriptable scripttable = cx.initStandardObjects();
       
/**** 用例3 ***/
Object result = cx.evaluateString(scripttable, str, null, 1, null);
String res = Context.toString(result);
System.out.println("result=="+res);
       
/**** 用例4 ***/
Script script = cx.compileString(str, null, 1, null);
Object result2 = script.exec(cx, scripttable);
System.out.println("result=="+result2);

 

参考

Mozilla官方文档:

http://www.mozilla.org/rhino/

Oracle的工具行工具:

http://docs.oracle.com/javase/6/docs/technotes /tools/share/jrunscript.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值