Java Reference
In-Depth Information
Listing 5-6. Implementing a Java Interface Using Top-Level Functions in Script
// UsingInterfaces.java
package com.jdojo.script;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class UsingInterfaces {
public static void main(String[] args) {
// Get the Nashorn engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// Make sure the script engine implements Invocable
// interface
if (!(engine instanceof Invocable)) {
System.out.println(
"Interface implementation in script" +
"is not supported.");
return;
}
// Cast the engine reference to the Invocable type
Invocable inv = (Invocable) engine;
// Create the script for add() and subtract() functions
String scriptPath = "calculatorasfunctions.js";
try {
// Compile the script that will be stored in the
// engine
engine.eval("load('" + scriptPath + "')");
// Get the interface implementation
Calculator calc =
inv.getInterface(Calculator.class);
if (calc == null) {
System.err.println("Calculator interface " +
"implementation not found.");
return;
}
 
Search WWH ::




Custom Search