W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
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); } }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: