Rhino-1.7.7.jar Package Required
code example:
PackageCn.java.mozilla.javascript;ImportOrg.mozilla.javascript.Context;Importorg.mozilla.javascript.Scriptable; Public classTest { Public Static voidMain (string[] args) {test4jsnormalcode (); Test4jsobj (); Test4jsfunc (); Test4jsfuncwithparam (); } protected Static voidTest4jsnormalcode () {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); } protected Static voidtest4jsobj () {Context CTX=Context.enter (); scriptable Scope=ctx.initstandardobjects (); String Jsstr= "var objtest = {' Key1 ': ' value1 '}; Objtest.key1; "; Object result= ctx.evaluatestring (scope, JSSTR,NULL, 0,NULL); System.out.println ("Result=" +result); } protected Static voidTest4jsfunc () {Context CTX=Context.enter (); scriptable Scope=ctx.initstandardobjects (); String Jsstr= "var testFunc = function () {return ' TestFunc ... '}; TestFunc (); "; Object result= ctx.evaluatestring (scope, JSSTR,NULL, 0,NULL); System.out.println ("Result=" +result); } protected Static voidTest4jsfuncwithparam () {Context CTX=Context.enter (); scriptable Scope=ctx.initstandardobjects (); Scope.put ("param1", Scope, "value1"); String Jsstr= "var testFunc = function (param) {return ' TestFunc ... ' + ' param= ' +param}; TestFunc (param1); "; Object result= ctx.evaluatestring (scope, JSSTR,NULL, 0,NULL); System.out.println ("Result=" +result); }}
Output results
result=200Result=Value1result=testfunc...result=testfunc...param=value1
Java util-executing JavaScript code tools in Java code Rhino-1.7.7.jar