Created
June 25, 2014 16:46
-
-
Save tamast/273595324147b52706ce to your computer and use it in GitHub Desktop.
Calling java code from javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
import javax.script.ScriptEngine; | |
import javax.script.ScriptEngineManager; | |
import javax.script.ScriptException; | |
public class TestMain { | |
public static void main(String[] args) throws ScriptException { | |
ScriptEngineManager factory = new ScriptEngineManager(); | |
ScriptEngine engine = factory.getEngineByName("JavaScript"); | |
Map<String, Object> bindings = new HashMap<String, Object>(); | |
bindings.put("test1", new Test1()); | |
bindings.put("test2", new Test2()); | |
for (String key : bindings.keySet()) { | |
engine.put(key, bindings.get(key)); | |
} | |
/* Print: | |
* Doing something in javascript here first | |
* Back in java code here: javascript value is bar | |
*/ | |
engine.eval("println('Doing something in javascript here first');" | |
+ "var test = test2.apply('bar');" | |
+ "test1.apply(test);"); | |
} | |
public static class Test1 { | |
public void apply(String s) { | |
System.out.println("Back in java code here: " + s); | |
} | |
} | |
public static class Test2 { | |
public String apply(String s) { | |
return "javascript value is " + s; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment