Calls between Java and Js based ScriptEngineManager class, this class is jdk8 added:
import java.io.File; import java.util.ArrayList; import java.util.List; import javax.script.Bindings; import javax.script.Invocable; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.SimpleScriptContext; import org.junit.Test; public class JavaScriptFunction { @Test public void print() throws Exception{ ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); engine.eval("print('hello word!!')"); } @Test public void obj() throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); StringBuffer script = new StringBuffer(); script.append("var obj = new Object();"); script.append ( "obj.hello = function (name) {Print ( 'Hello,' + name);}" ); // implementation of this script script engine.eval (script.toString ()); // the javax. script.Invocable is an optional interface // check your script engine interface is realized! // Note: JavaScript engine implements the interface Invocable Invocable inv = (Invocable) Engine; // get js we want to call that method belongs object object obj = engine.get ( "obj" ); // method called hello execution object obj inv.invokeMethod (obj, "hello", "Script method, !!" ); } @Test public void file() throws Exception{ ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); engine.eval(new java.io.FileReader(new File("F:/test/test.js"))); Invocable inv = (Invocable) engine; Object obj = engine.get("obj"); inv.invokeMethod (obj, "name", "know" ); } /** * Script variables * @throws Exception */ @Test public void scriptVar() throws Exception{ ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); File File = new new File ( "F.: /Test/test.txt" ); // File object f js injected directly into the script and can be used as a global variable engine.put ( "Files" , File); engine.eval("print(files.getPath());print(files.getName());"); } /** * Use Script achieve java interfaces * @throws Exception */ public void runnableImpl() throws Exception{ ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); // String script defined in JavaScript code String = Script "RUN function () {Print ( 'RUN Called');}" ; // implementation of the script engine.eval (script); // Get Runnable interface object (instance) from the script engine. The interface method implemented by the script function with a matching name. Inv = Invocable (Invocable) Engine; // In the above script, we have implemented the Runnable interface run () method Runnable Runnable = inv.getInterface (Runnable. Class ); // start a thread to run a script to achieve the above script runnable interfaces of the Thread the Thread = new new the Thread (runnable); thread.start(); } /** * Script engine more scope * @throws Exception */ @Test public void multiScopes() throws Exception{ ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("nashorn"); // 打印全局变量 "x" engine.put("x", "hello word!!"); engine.eval ( "Print (X);" ); // The above code will print "hello word !!" // now, passing a different context Script ScriptContext context = new new SimpleScriptContext (); // New Script context of binding ScriptContext the ENGINE_SCOPE of Bindings Bindings = context.getBindings (ScriptContext.ENGINE_SCOPE); // add a new face changing to a new range engineScope in bindings.put ( "the X-", "Word the Hello !!" ); // execute the same script - but this time passing in a different context Script engine.eval ( " Print (X); " , Bindings); engine.eval("print(x);"); } public static void main(String[] args) throws Exception { new JavaScriptFunction().runnableImpl(); List list = new ArrayList(); list.add("1"); list.add("1"); list.add("1"); for (Object object : list) { System.out.println(object); } } }
The use packaging technology in Java will run js script encapsulation:
import java.io.FileNotFoundException; import java.io.FileReader; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; /** * Run the script * @author Ruby * */ public class RunScript { private ScriptEngineManager manager = new ScriptEngineManager(); private ScriptEngine engine; private String fileName; public RunScript(String fileName){ engine = manager.getEngineByName("JavaScript"); this.fileName = fileName; } /** * Set the variable * @param varName * @Param obj * / public void setVar (String to varName, the Object obj) { engine.put(varName, obj); } /** * Startup script * @throws FileNotFoundException * @throws ScriptException */ public void start() throws FileNotFoundException, ScriptException{ engine.eval(new FileReader(fileName)); } }
test
The Logger object is injected into the js object, then you can use java in the Logger object in the js file:
public static void main(String[] args) throws Exception { RunScript rs = new RunScript("D:\test.js"); rs.setVar("Logger", Logger.getLogger(ConsoleListener.class)); rs.start(); }
Extended:
Use ScriptEngineManager JSON string class is determined whether valid:
ScriptEngineManager sem = new ScriptEngineManager (); ScriptEngine se = sem.getEngineByName ("js"); String jsonstr = "({name: 1, obj: 3,[dd]})"; try { System.out.println (se.eval (jsonstr)); } catch (ScriptException e) { System.out.println ( "malformed json" ); }
other methods:
package util; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; public class Test { public static void main(String[] args) { try { JSONObject.parse("{'a':1 'b':1}"); } catch (JSONException e) { System.out.println ( "Error the JSON String" ); } } }