Java Scripting API允許我們以腳本語(yǔ)言實(shí)現(xiàn)Java接口。
假設(shè)我們想在Javascript中實(shí)現(xiàn)下面的Java接口。
public interface Calculator { double add (double n1, double n2); }
cal.js文件的內(nèi)容,保存在c:/Java_dev/cal.js下
function add(n1, n2) { n1 + n2; }
從Java代碼調(diào)用JavaScript中實(shí)現(xiàn)的Java接口。
import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Main { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); if (!(engine instanceof Invocable)) { System.out.println("Interface implementation in script" + "is not supported."); return; } Invocable inv = (Invocable) engine; String scriptPath = "c:/Java_Dev/cal.js"; engine.eval("load("" + scriptPath + "")"); Calculator calc = inv.getInterface(Calculator.class); if (calc == null) { System.err.println("Calculator interface " + "implementation not found."); return; } double x = 2.0; double y = 1.0; double addResult = calc.add(x, y); System.out.println(addResult); } }
更多建議: