Java脚本教程 – Java脚本实现接口
在脚本中实现Java接口
Java Scripting API允许我们以脚本语言实现Java接口。
例子
假设我们想在Javascript中实现下面的Java接口。
public interface Calculator { double add (double n1, double n2); }
cal.js文件的内容,保存在c:/Java_dev/cal.js下
function add(n1, n2) { n1 + n2; }
从Java代码调用JavaScript中实现的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); } }