Import Java.lang.*;import java.util.arrays;import Java.util.list;import Javax.script.invocable;import Javax.script.scriptengine;import Javax.script.scriptenginemanager;public class Scriptenginetest {public static void Main (string[] args) throws Exception {Scriptenginemanager sem = new Scriptenginemanager (); ScriptEngine engine = Sem.getenginebyname ("javascript"); Python or Jython, <pre name= "code" class= "HTML" >//into the context of the variable engine.put ("msg", "Just a Test"); Defines the class user String str = "MSG + = '!!! '; var user = {name: ' Tom ', age:23,hobbies:[' football ', ' Basketball ']}; "; Engine.eval (str); Takes a value from the context engine String msg = (string) engine.get ("msg"); String name = (string) engine.get ("name"); string[] HB = Engine.get ("HB"); SYSTEM.OUT.PRINTLN (msg); SYSTEM.OUT.PRINTLN (name + ":" + hb[0]); Defines the mathematical function engine.eval ("function add (A, b) {c = a + B; return C; }"); Get the Calling interface invocable Jsinvoke = (invocable) engine; Define an addition function Object RESULT1 = jsinvoke.invokefunction ("Add", new object[] {10, 5}); System.out.println (RESULT1); Call the addition function, pay attention to the method of Adder Adder = Jsinvoke.getinterface (Adder.class); int result2 = Adder.add (10, 35); System.out.println (RESULT2); Define the Run () function Engine.eval ("function run () {print (' www.java2s.com ');}"); Invocable invokeengine = (invocable) engine; Runnable runner = Invokeengine.getinterface (Runnable.class); Thread t = new Thread (runner) that defines threading execution; T.start (); T.join (); Import other Java packages String Jscode = "Importpackage (java.util); var list2 = arrays.aslist ([' A ', ' B ', ' C ']); "; Engine.eval (Jscode); List<string> List2 = (list<string>) engine.get ("List2"); for (String val:list2) {System.out.println (val);} }}
The scripting engine provides good extensibility for implementing dynamic functions, such as plug-in mechanisms.
Documentation for the engine interface:
ScriptEngine
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
JDK8 dynamically define and run code in the Java Transfer JavaScript scripting engine