Implementing an interface from script
suggest changeimport java.io.FileReader;
import java.io.IOException;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class InterfaceImplementationExample {
public static interface Pet {
public void eat();
}
public static void main(String[] args) throws IOException {
// Nashorn was included in Java 8 through 14 and removed in Java 15.
// getEngineByName returns null when it is absent; eval then throws NullPointerException.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
try {
// pet.js is a file in the working directory, not the comment below.
// The binary name of the nested type uses '$', not '.'.
/*
var Pet = Java.type("InterfaceImplementationExample$Pet");
new Pet() {
eat: function() { print("eat"); }
}
*/
Pet pet = (Pet) engine.eval(new FileReader("pet.js"));
pet.eat();
} catch (ScriptException ex) {
ex.printStackTrace();
}
// Outcome:
// 'eat' printed on standard output
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents