Skip to content

Instantly share code, notes, and snippets.

@theaspect
Created March 4, 2015 07:32
Show Gist options
  • Save theaspect/480f0566b9540d158d55 to your computer and use it in GitHub Desktop.
Save theaspect/480f0566b9540d158d55 to your computer and use it in GitHub Desktop.
Nashorn two-way binding
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.lang.reflect.InvocationTargetException;
public class Script {
public static void main(String... args) throws ScriptException, IllegalAccessException, InvocationTargetException, InstantiationException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("" +
"var Integration = Java.type('Script.Integration');\n" +
"var intObject = new Integration();\n" +
"print('SCRIPT Return from echo: ' + intObject.echo('Hello world'));\n" +
"intObject.info('someInfo');\n" +
"intObject.callback = function(name,info){print('SCRIPT callback{name:\"'+name+'\",info:\"'+info+'\"}')}\n" +
"intObject.info('someInfo');\n"
);
}
public static class Integration {
Callback callback;
String info;
public String echo(String out) {
System.out.println("JAVA echo");
return out;
}
public void info(String info) {
System.out.println("JAVA setInfo");
this.info = info;
if (callback != null) {
callback.onEvent("callback method", info);
} else {
System.out.println("JAVA No callback registered");
}
}
public void setCallback(Callback callback) {
System.out.println("JAVA setCallback");
this.callback = callback;
}
public Callback getCallback() {
System.out.println("JAVA getCallback");
return callback;
}
}
@FunctionalInterface
public interface Callback {
public abstract void onEvent(String name, String param);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment