As we've seen earlier to invoke the scripting engine to execute JavaScript in Java, let's look at how to invoke the Java object in JavaScript after binding the object to the script engine.
Use the following example:
Import Java.util.HashMap; Import Java.util.Map; Import Java.util.logging.Level; Import Java.util.logging.Logger; Import javax.script.Bindings; Import javax.script.Invocable; Import Javax.script.ScriptContext; Import Javax.script.ScriptEngine; Import Javax.script.ScriptEngineManager; Import javax.script.ScriptException; /** * * @author ZCB/public class SuperTest {public static void main (string[] args) {Scriptenginemanager sem = new SCR Iptenginemanager (); ScriptEngine SE = null; SE = sem.getenginebyextension ("JS"); Se=sem.getenginebymimetype ("Text/javascript"); Se=sem.getenginebyname ("JavaScript"); String JSScript = "function mytest () {" + "println (contextproperties);" + "Contextproperties.remove (' three ');" + "println (contextproperties); " + "println" (' 1: ' +contextproperties.containskey (' one ')); "+" println (' 2: ' +contextproperties.containskey (' four ')); " "println (' Size: ' +contextproperties.size ());" + "println (Contextproperties.get (' one '));" + "return ( Contextproperties.get (' one '); Contextproperties.get (' two '))? True:false;} "; /can also call other methods of the bound object, such as the method of the custom object bindings bindings = Se.getbindings (Scriptcontext.engine_scope); Map map = new HashMap (); Map.put ("One", 1); Map.put ("Two", 5); Map.put ("three", 5); Bindings.putall (map); System.out.println ("One:" +bindings.get ("one")); System.out.println ("Two:" +bindings.get ("two")); Bind a Map object, or you can bind a custom Java object Bindings.put ("Contextproperties", map); try {Object flag = null; Se.eval (jsscript, bindings); if (se instanceof invocable) {invocable invoke = (invocable) se; f lag = invoke.invokefunction ("mytest"); System.out.println ("flag:" + flag);} Outputs the modified Map object System.out.println ("map:" +map) after JavaScript; catch (Nosuchmethodexception ex) {Logger.getlogger (SuperTest.class.getName ()). log (Level.severe, NULL, ex);} catch ( Scriptexception ex) {Logger.getlogger (SuperTest.class.getName ()). log (Level.severe, NULL, ex);} }
The output results are as follows:
{two=5, one=1, three=5}
{two=5, one=1}
1:true
2:false
Size:2
1
Flag:false
Map:{two=5, one=1} Note: Changes to Java objects in JS are also effective come on Oh ~
In this way, we implement Java invoke JavaScript, and JavaScript calls Java to implement the circular call.