javascript
java rhino import_java调用javascript :js引擎rhino
前段時(shí)間,在瀏覽javaeye論壇,看見(jiàn)有人征集如何在java中運(yùn)行數(shù)學(xué)表達(dá)式。
結(jié)果方案五花八門(mén):
1.jakarta commons JEXL.
2.Beanshell
3.Java Math Expression Parser jep
4.parse combinator jparsec
5.jdk 6.0的 script
6.利用SQL
7.自己寫(xiě)語(yǔ)法分析
如果自己寫(xiě)語(yǔ)法分析,沒(méi)有個(gè)2000行估計(jì)搞不定。有人用sql來(lái)運(yùn)行數(shù)學(xué)表達(dá)式,比較另類。
不過(guò)由于前段時(shí)間較深入的學(xué)習(xí)了一些java的javascript引擎,我給出的方案就是用javascript來(lái)計(jì)算了。
java中比較著名的js引擎當(dāng)屬mozilla開(kāi)源的rhino,不過(guò)jdk6已經(jīng)把它收歸帳下,成了正規(guī)軍。
public class MathEval
{
public static void main(String[] args)
{
Context cx = Context.enter();
try
{
Scriptable scope = cx.initStandardObjects();
String str = "9*(1+2)";
Object result = cx.evaluateString(scope, str, null, 1, null);
double res = Context.toNumber(result);
System.out.println(res);
}
finally
{
Context.exit();
}
}
}
下面總結(jié)一下前段時(shí)間學(xué)習(xí)rhino的心得(給自己的程序添加腳本功能,其實(shí)是很酷的):
一:環(huán)境配置及運(yùn)行js腳本:
在?http://www.mozilla.org/rhino/?下載rhino:
把js.jar加入系統(tǒng)CLASSPATH中
可以以交互模式調(diào)用js解釋器:
java org.mozilla.javascript.tools.shell.Main
然后您應(yīng)該會(huì)看到解釋器的版本號(hào),后面跟著提示符 js>
用法如下:
比如:有一個(gè)js文件:
D:\eclipse-workshop\rhinoExample\src\isPrime.js
內(nèi)容如下:
js 代碼
function isPrime (num)
{
if (num <= 1) {
print("Please enter a positive integer >= 2.")
return false
}
var prime = true
var sqrRoot = Math.round(Math.sqrt(num))
for (var n = 2; prime & n <= sqrRoot; ++n) {
prime = (num % n != 0)
}
return prime
}
如何運(yùn)行呢:
1:在命令行下鍵入:
java org.mozilla.javascript.tools.shell.Main
2:在js〉下鍵入:
load("D:/eclipse-workshop/rhinoExample/src/isPrime.js");
注意:是“/”而不是“\”
3:鍵入:
isPrime(77);
可看見(jiàn)返回結(jié)果為false。
鍵入:
isPrime(71);返回true
再給個(gè)例子,腳本如下:
person = {
name:"Mike Squillace",
age:37,
position:"software engineer",
getFirstName:function () {return this.name.split(" ")[0]}
}
person.getFirstName()
js產(chǎn)生swing的例子:
load("D:/eclipse-workshop/rhinoExample/src/SwingApplication.js");
怎么樣?看見(jiàn)效果沒(méi)?是不是很強(qiáng)悍?其中SwingApplication.js是rhnio自帶的例子。
Rhino還有一個(gè)js腳本的調(diào)試器:
Rhino JavaScript Debugger:
java org.mozilla.javascript.tools.debugger.Main [options] [filename.js] [script-arguments]
只須運(yùn)行java org.mozilla.javascript.tools.debugger.Main,就可以看到調(diào)試器的界面了。
為了加快js文件運(yùn)行的速度,可以把它編譯為class文件:
compile:
java org.mozilla.javascript.tools.jsc.Main D:/eclipse-workshop/rhinoExample/src/FirstCompile.js
編譯產(chǎn)生FirstCompile.class文件
在D:/eclipse-workshop/rhinoExample/src/下運(yùn)行該class文件:
java FirstCompile
二:在實(shí)際應(yīng)用中不可避免的需要遇到j(luò)ava代碼如何和javascript腳本相互訪問(wèn)的問(wèn)題:
這是一個(gè)最簡(jiǎn)單的例子:(liveConnect.js是rhnio自帶的例子):
load("D:/eclipse-workshop/rhinoExample/src/liveConnect.js");
在給個(gè)復(fù)雜點(diǎn)的例子, 沒(méi)有什么邏輯,純技術(shù)展示,呵呵:
JSFunction.java:
java 代碼
package co.test;
import org.mozilla.javascript.Function;
public class JSFunction? //extends ScriptableObject
{
private String name;
private Function handle;
public void setHandler(Function func)
{
this.handle = func;
}
public Function getHandler()
{
return this.handle;
}
public JSFunction(String s)
{
this.name = s;
}
public static void print(String s)
{
System.out.println(s);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
JSExploration.java:
java 代碼
package co.test;
import java.io.FileReader;
import java.io.LineNumberReader;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
public class JSExploration
{
private Context cx;
private Scriptable scope;
public JSExploration()
{
this.cx = Context.enter();
this.scope = cx.initStandardObjects();
}
public Object runJavaScript(String filename)
{
String jsContent = this.getJsContent(filename);
Object result = cx.evaluateString(scope, jsContent, filename, 1, null);
return result;
}
private String getJsContent(String filename)
{
LineNumberReader reader;
try
{
reader = new LineNumberReader(new FileReader(filename));
String s = null;
StringBuffer sb = new StringBuffer();
while ((s = reader.readLine()) != null)
{
sb.append(s).append("\n");
}
return sb.toString();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public Scriptable getScope()
{
return scope;
}
public static void main(String[] args)
{
String filename = System.getProperty("user.dir") + "/jsmap.js";
JSExploration jsExploration = new JSExploration();
Object result = jsExploration.runJavaScript(filename);
Scriptable scope = jsExploration.getScope();
Scriptable obj = (Scriptable) scope.get("obj", scope);
System.out.println("obj.a == " + obj.get("a", obj));
Scriptable b = (Scriptable) obj.get("b", obj);
System.out.println("b[0] == " + b.get(0, b));
Boolean flag = (Boolean) scope.get("flag", scope);
System.out.println(flag);
Scriptable myobj = (Scriptable) scope.get("obj", scope);
Boolean myflag = (Boolean) scope.get("flag", scope);
System.out.println(myflag);
Scriptable jsFunction = (Scriptable) scope.get("jsFunction", scope);
Function fc = (Function) jsFunction.get("handler", jsFunction);
Object isPrime = fc.call(Context.getCurrentContext(), jsFunction, fc, new Object[] { "this is my test" });
}
}
js腳本:jsmap.js
js 代碼
var swingNames = JavaImporter();
swingNames.importPackage(Packages.java.lang);
swingNames.importPackage(Packages.co.test);
obj = {a:1, b:['x','y']}
next = isPrime
flag = isPrime(5)
with (swingNames) {
System.out.println("in javascript");
JSFunction.print("in JSFunction");
jsFunction = new JSFunction("lichunlei");
var name = jsFunction.getName();
System.out.println("get name from java source: " + name);
jsFunction.setHandler(log);
}
java.lang.System.out.println("not use swingNames");
function isPrime (num)
{
java.lang.System.out.println("in isPrime(num)");
if (num <= 1) {
java.lang.System.out.println("Please enter a positive integer >= 2.")
return false
}
var prime = true
var sqrRoot = Math.round(Math.sqrt(num))
for (var n = 2; prime & n <= sqrRoot; ++n) {
prime = (num % n != 0)
}
return prime
}
function log(msg)
{
java.lang.System.out.println("in function log: " + msg);
}
總結(jié)
以上是生活随笔為你收集整理的java rhino import_java调用javascript :js引擎rhino的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java 1.8 rpm_jdk1.8下
- 下一篇: mysql 免安装重装_MYSQL的免安