Java 腳本實(shí)現(xiàn)接口

2018-03-18 13:58 更新

Java腳本教程 - Java腳本實(shí)現(xiàn)接口

在腳本中實(shí)現(xiàn)Java接口

Java Scripting API允許我們以腳本語言實(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);
  }
}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號