Last active
August 29, 2015 14:03
-
-
Save tamast/b0e44ac1a9b1e128e121 to your computer and use it in GitHub Desktop.
Create java object in js
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') + ' ' + new java.lang.Integer(12345);" //creating java object in javascript. | |
+ "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