网页js代码可以改写成Java吗_Rhino-用纯Java写成的JavaScript的开放源代码实现

import javax.script.ScriptEngine;

import javax.script.ScriptEngineManager;

import javax.script.ScriptException;

import org.mozilla.javascript.Context;

import org.mozilla.javascript.Scriptable;

//http://www.cnblogs.com/cczw/archive/2012/07/16/2593957.html

//http://www.oschina.net/p/rhino/

//Rhino是用纯Java写成的JavaScript的开放源代码实现。它最常被用于嵌入Java应用程序,以便为终端用户提供脚本的能力。

//开源下载:https://github.com/downloads/mozilla/rhino/rhino1_7R4.zip

//http://www.iteye.com/topic/87423

//http://blog.csdn.net/szwangdf/article/details/25376415

//http://blog.csdn.net/ycyangcai/article/details/6452143

public class TestJs {

public static void main(String[] args) {

Context ctx = Context.enter();

Scriptable scope = ctx.initStandardObjects();

String jsStr = "100*20/10";

Object result = ctx.evaluateString(scope, jsStr, null, 0, null);

System.out.println("result=" + result);

ctx.exit();

test001();

test002();

test003();

}

private static void test003() {

try {

ScriptEngineManager factory = new ScriptEngineManager();

ScriptEngine engine = factory.getEngineByName("JavaScript");

engine.eval("print('Hello World')");

} catch (ScriptException e) {

e.printStackTrace();

}

}

private static void test002() {

Context ctx = Context.enter(); // 获取环境设置

Scriptable scope = ctx.initStandardObjects(); // 初始化本地对象

scope.put("x", scope, new Integer(20)); // 输入参数设置

scope.put("y", scope, new Integer(30));

try {

ctx.evaluateString(scope, "var result=x+y", "", 1, null); // 执行

System.out.println(scope.get("result", scope)); // 结果输出

} finally {

Context.exit();

}

}

private static void test001() {

Context cx = Context.enter();

try {

String s = "var c = 100 + 200";

Scriptable so = cx.initStandardObjects();

cx.evaluateString(so, s, "ex-1", 1, null);

System.out.println("result=" + so.get("c", so));

} finally {

cx.exit();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值