Created
December 27, 2016 08:00
-
-
Save frsyuki/dd22e59540ed407296ea1ed7f58b9129 to your computer and use it in GitHub Desktop.
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.Bindings; | |
import javax.script.Invocable; | |
import javax.script.ScriptContext; | |
import javax.script.ScriptEngine; | |
import javax.script.ScriptEngineManager; | |
import javax.script.ScriptException; | |
import javax.script.SimpleBindings; | |
import jdk.nashorn.api.scripting.NashornScriptEngineFactory; | |
public class Jx | |
{ | |
public static void main(String[] args) throws Exception | |
{ | |
NashornScriptEngineFactory jsEngineFactory = new NashornScriptEngineFactory(); | |
ScriptEngine jsEngine = jsEngineFactory.getScriptEngine(new String[] { | |
//"--language=es6", | |
"--no-java", | |
"--no-syntax-extensions", | |
"-timezone=UTC", | |
}); | |
Map<String, String> params = new HashMap<>(); | |
params.put("a", "vA"); | |
params.put("b", "vB"); | |
Bindings bindings = new SimpleBindings(); | |
bindings.put("params", new JavaParamsProvider(params)); | |
jsEngine.setBindings(bindings, ScriptContext.GLOBAL_SCOPE); | |
StringBuilder contextCode = new StringBuilder(); | |
contextCode.append("({\n"); | |
for (String key : params.keySet()) { | |
contextCode | |
.append("get ").append(key).append(" () {") | |
.append(" return params.getJavaParam('").append(key).append("') ") | |
.append("},"); | |
} | |
contextCode.append("})"); | |
jsEngine.eval("function invoke(contextCode, source) { return (new Function(\"with(this){\\nreturn (\" + source + \")}\\n\")).call(eval(contextCode)) }"); | |
Invocable inv = (Invocable) jsEngine; | |
String ret = (String) inv.invokeFunction("invoke", contextCode.toString(), "a + b"); | |
System.out.println("a + b = " + ret); //=> vAvB | |
} | |
public static class JavaParamsProvider | |
{ | |
private final Map<String, String> params; | |
public JavaParamsProvider(Map<String, String> params) | |
{ | |
this.params = params; | |
} | |
public String getJavaParam(String name) | |
{ | |
return params.get(name); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment