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

相关推荐