Created
May 12, 2015 21:36
-
-
Save RaffaeleSgarro/4cb135be73f3d3a0424e to your computer and use it in GitHub Desktop.
Rhino: read Javascript numbers returned from Java method
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
package stackoverflow; | |
import sun.org.mozilla.javascript.internal.Context; | |
import javax.script.ScriptEngine; | |
import javax.script.ScriptEngineManager; | |
import java.util.Date; | |
/* | |
* See question at http://stackoverflow.com/q/30185079/315306 | |
* | |
* Program output: | |
* | |
* Result: 1 (java.lang.Integer) | |
* Result: 9.0 (java.lang.Double) | |
*/ | |
public class RhinoHowToReadJavascriptNumbersFromJavaMethod { | |
public static void main(String... args) throws Exception { | |
ScriptEngineManager mgr = new ScriptEngineManager(); | |
ScriptEngine engine = mgr.getEngineByName("JavaScript"); | |
try { | |
Context ctx = Context.enter(); | |
ctx.getWrapFactory().setJavaPrimitiveWrap(false); | |
engine.put("Conf", new Configuration()); | |
dumpResult(engine.eval("Conf.read('numbers.one')")); | |
dumpResult(engine.eval("(Conf.read('numbers.one') + Conf.read('numbers.two')) * Conf.read('numbers.three')")); | |
} finally { | |
Context.exit(); | |
} | |
} | |
private static void dumpResult(Object res) { | |
System.out.printf("Result: %s (%s)%n", res, res != null ? res.getClass().getName() : null); | |
} | |
public static class Configuration { | |
public Object read(String key) { | |
Object result; | |
switch (key) { | |
case "numbers.one": | |
result = 1; | |
break; | |
case "numbers.two": | |
result = 2; | |
break; | |
case "numbers.three": | |
result = 3; | |
break; | |
case "strings.four": | |
result = "4"; | |
break; | |
case "dates.today": | |
result = new Date(); | |
break; | |
default: | |
result = null; | |
break; | |
} | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment