I'm using ScriptEngine to run a Javascript. In my case, the Javascript will always return a boolean. I thought that eval() would return an Object that I can cast, but instead it seems to return a ScriptObjectMirror
. toString() returns [Boolean true]
, so the evaluation is working. How can I convert or cast to a Boolean or boolean?
Here is my code
final ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByName("javascript");
final Object jsEval = engine.eval(String.format("new Boolean(%s)", jsString));
System.out.printf("*** jsEval: %s %s%n ", jsEval, jsEval.getClass().getName());
Output is
*** jsEval: [Boolean true] jdk.nashorn.api.scripting.ScriptObjectMirror
If you know the type for sure, you can use the to
method:
jsEval.to(Boolean.class)