Skip to content

Instantly share code, notes, and snippets.

@dragon0
Created February 12, 2015 01:44
Show Gist options
  • Save dragon0/ed84ce45dcba0516d04a to your computer and use it in GitHub Desktop.
Save dragon0/ed84ce45dcba0516d04a to your computer and use it in GitHub Desktop.
Cast an object defined in a script to a Java Interface
import javax.script.*;
public class ScriptInterfaceCast{
public static void main(String[] args) throws Exception{
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine rhino = manager.getEngineByName("javascript");
String script
= "function JSRunnable(){\n"
+ " this.run = function(){\n"
+ " java.lang.System.out.println(\"Hello from JS Runnable\");\n"
+ " }\n"
+ "}\n"
+ "myJSRunnable = new JSRunnable();\n"
+ "\n";
rhino.eval(script);
Runnable myJSRunnable = ((Invocable)rhino).getInterface(
rhino.get("myJSRunnable"),
Runnable.class);
myJSRunnable.run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment