Sometimes because of the need, we want to call the JS method in Java, is no longer like a page in the event trigger, how to do it. This afternoon there is no time for small research, and now share with you. Wrong place, hope everybody correct, common progress.
* * Load script engine, and call JS method in Java/public void Test2 () {Scriptenginemanager manager = new Scriptenginemanager (); ScriptEngine engine = Manager.getenginebyname ("javascript"); try {String str= "2&1"; Double d = (double) engine.eval (str); Integer I=d.intvalue (); System.out.println (i); catch (Scriptexception ex) {ex.printstacktrace ();}}
/* * In Java called js,jdk1.6 has loaded the JS engine class, and then it calls the JS method. * and the parameter assignment in the script's method via the JDK/public void Test (String name) {Scriptenginemanager sem = new Scriptenginemanager ();/* *sem The. Getenginebyextension (string extension) parameter is a JS sem.getenginebymimetype (string mimetype) parameter is Application/javascript or Text/javascript sem.getenginebyname (String shortname) parameter to JS or JavaScript or JavaScript/scriptengine SE = Sem.getenginebyname ("JS"); try {String script = "function say () {return ' Hello, '" +name+ ";}"; Se.eval (script); Invocable inv2 = (invocable) se; String res= (String) inv2.invokefunction ("Say", name); System.out.println (RES); catch (Exception e) {e.printstacktrace ();}}
* * Demonstrates how to use Java objects as global variables in JS, and demonstrates assigning a file class to a scripting language and obtaining its properties. * * public void Testscriptvariables () {Scriptenginemanager sem=new scriptenginemanager (); ScriptEngine engine=sem.getenginebyname ("JS"); File File=new file ("C://1.txt"); Engine.put ("F", file); try {engine.eval (' println (' Path: ' +f.getpath ()) ');/cannot use alert method} catch (Scriptexception e) {e.printstacktrace ();}}
* * Demonstrates how to start a JS method with threads in Java * * public void Testscriptinterface () throws scriptexception {Scriptenginemanager sem=new S Criptenginemanager (); ScriptEngine engine=sem.getenginebyname ("JS"); String script= "var obj=new Object (); Obj.run=function () {println (' Test Thread ')}"; Engine.eval (script); Object Obj=engine.get ("obj");//Get JS invocable inv= (invocable) engine; Runnable R=inv.getinterface (Obj,runnable.class); Thread t=new thread (r); T.start (); }
So Java can execute dynamic language, but note is jdk1.6 version of Oh ~