1. package co.test;
2.
3. import java.io.FileReader;
4. import java.io.LineNumberReader;
5.
6. import org.mozilla.javascript.Context;
7. import org.mozilla.javascript.Function;
8. import org.mozilla.javascript.Scriptable;
9.
9.public class JSExploration
9.{
9. private Context cx;
9.
9. private Scriptable scope;
9.
9. public JSExploration()
9. {
9. this.cx = Context.enter();
9. this.scope = cx.initStandardObjects();
9. }
9.
9. public Object runJavaScript(String filename)
9. {
9. String jsContent = this.getJsContent(filename);
9. Object result = cx.evaluateString(scope, jsContent, filename, 1, null);
9. return result;
9. }
9.
9. private String getJsContent(String filename)
9. {
9. LineNumberReader reader;
9. try
9. {
9. reader = new LineNumberReader(new FileReader(filename));
9. String s = null;
9. StringBuffer sb = new StringBuffer();
9. while ((s = reader.readLine()) != null)
9. {
9. sb.append(s).append("\n");
9. }
9. return sb.toString();
9. }
9. catch (Exception e)
9. {
9. // TODO Auto-generated catch block
9. e.printStackTrace();
9. return null;
9. }
9. }
9.
9.
9. public Scriptable getScope()
9. {
9. return scope;
9. }
9.
9. public static void main(String[] args)
9. {
9. String filename = System.getProperty("user.dir") + "/jsmap.js";
9. JSExploration jsExploration = new JSExploration();
9. Object result = jsExploration.runJavaScript(filename);
9. Scriptable scope = jsExploration.getScope();
9.
9. Function sum = (Function) scope.get("sum", scope);
9. Function isPrime = (Function)sum.call(Context.getCurrentContext(), scope, sum, new Object[] {2,8});
9. Object ss = isPrime.call(Context.getCurrentContext(), sum, isPrime, new Object[] {2,8});
9. System.out.println(Context.toString(ss));
9.
9. }
9. }
试验了一个java 调用 javascript 的例子,如果把jsmap.js中的与this 有关的代码注销的话程序就可以正常运行。不住销掉的话就会报个运行时错误。。。
js 代码如下(有关this 的代码已注销):
1. function sum(x, y) {
2.// this.formulaeObject = null;
3.// this.formulaeObject["vager"] = function (c, d) {
// return (c + d)/2;
4.// };
5. var vager = 1000;
6. return function (x,y){return x + y + vager;} ;
7. }
8.
发表于 @ 2008年01月11日 10:03:00|评论(loading...)|编辑