ImportJava.io.File;ImportJava.lang.reflect.Field;Importjava.util.Arrays;Importjavax.script.Invocable;ImportJavax.script.ScriptEngine;ImportJavax.script.ScriptEngineManager;Importjavax.script.ScriptException; Public classJavaexecscriptdemo { Public Static voidMain (string[] args) {System.out.println (Jsobjfunc ()); System.out.println (Arrays.tostring (GetArray ())); System.out.println (Jscalculate ("A=1+2+3+ (2*2)")); Jsfunction (); Jsvariables (); } /*** Run the function in JS object * *@return */ Public StaticObject Jsobjfunc () {String script= "var obj={run:function () {return ' run method:return:\ ' abc ' +this.next (' test ') + ' \ ';},next:function (str) {return ' I came to next function ' +str+ ') '} '; Scriptenginemanager sem=NewScriptenginemanager (); ScriptEngine ScriptEngine= Sem.getenginebyname ("JS"); Try{scriptengine.eval (script); Object Object= Scriptengine.get ("obj"); Invocable Inv2=(invocable) ScriptEngine; return(String) Inv2.invokemethod (object, "Run"); } Catch(Exception e) {e.printstacktrace (); } return NULL; } /*** Get JS Object Number Type attribute * *@return */ Public Staticobject[] GetArray () {Scriptenginemanager sem=NewScriptenginemanager (); String Script= "var obj={array:[' test ', true,1,1.0,2.11111]}"; ScriptEngine ScriptEngine= Sem.getenginebyname ("JS"); Try{scriptengine.eval (script); Object Object2= Scriptengine.eval ("Obj.array"); Class<!--?--> Clazz =Object2.getclass (); Field Densefield= Clazz.getdeclaredfield ("Dense"); Densefield.setaccessible (true); return(object[]) densefield.get (OBJECT2); } Catch(Exception e) {e.printstacktrace (); } return NULL; } /*** JS Calculation * *@paramScript *@return */ Public StaticObject jscalculate (String script) {Scriptenginemanager manager=NewScriptenginemanager (); ScriptEngine Engine= Manager.getenginebyname ("javascript"); Try { return(Object) engine.eval (script); } Catch(Scriptexception ex) {ex.printstacktrace (); } return NULL; } /*** Run JS basic function*/ Public Static voidjsfunction () {Scriptenginemanager sem=NewScriptenginemanager (); ScriptEngine SE= Sem.getenginebyname ("javascript"); Try{String Script= "function say (name) {return ' Hello, ' +name;}"; Se.eval (script); Invocable Inv2=(invocable) se; String Res= (String) inv2.invokefunction ("Say", "test"); System.out.println (RES); } Catch(Exception e) {e.printstacktrace (); } } /*** JS in the use of variables*/ Public Static voidJsvariables () {Scriptenginemanager sem=NewScriptenginemanager (); ScriptEngine Engine= Sem.getenginebyname ("javascript"); File File=NewFile ("/data/js.txt"); Engine.put ("File", file); Try{engine.eval ("Println (' Path: ' +file.getabsolutefile ())"); } Catch(scriptexception e) {e.printstacktrace (); } }}
Java uses the scripting engine to execute JS