尝试了一下在Java 中使用rhino引擎,运行JavaScript脚本,现在将使用方法整理如下:
1.下载rhino引擎的文件,最后我获取到的是一个 js.jar 文件
2.将这个文件添加到 工程的 Libraries 中去,如图:
3.运行脚本并测试
//package test;
//导入的这两个包的路径和网上的有些不同,网上的时sun开头的
//但是我经过尝试发现,不存在这个包,因此后来修改成如下路径
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
public class Test {
//一个简单的类,用于测试
public static class HelloWorld {
String s = "Hello World";
public void sayHello(){
System.out.println(s);
}
public void putstring(String s1){
System.out.println(s1);
}
}
public static void main(String[] args) {
//创建类对象
HelloWorld hello = new HelloWorld();
//使用rhino的一些初始化操作
Context cx = Context.enter();
try{
Scriptable scope = cx.initStandardObjects();
//写入JS脚本
String str="function a(x,y){var result; while(x<69600){x=x+y;y++;}return x} x =10;y=20; a(x,y);";
//执行脚本
Object result = cx.evaluateString(scope, str, null, 1, null);
//实现JAVA中的变量与js中的变量绑定
//使用的是 put 方法 ,第一个参数为 JS中的变量名称,第三个参数为java中的对象
scope.put("script_hello",scope, hello);
//一段经过混淆的js代码
str="(function(p,a,c,k,e,r){e=String;if('0'.replace(0,e)==0){while(c--)r[e(c)]=k[c];k=[function(e){return r[e]||e}];e=function(){return'^$'};c=1};
while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('x*y;',[],1,''.split('|'),0,{}))";
str = "script_hello.putstring("+ str + ")";
//调用JAVA的类方法
cx.evaluateString(scope, str, null, 1, null);
//输出结果
System.out.println(Context.toString(result));
}
finally{
Context.exit();
}
}
}