0

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

1 Answer 1

1

If you know the type for sure, you can use the to method:

jsEval.to(Boolean.class)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Love when it's such a simple solution. Obviously, I need to cast to ScriptObjectMirror. Why does eval() return an Object instead of returning ScriptObjectMirror, or at least some interface
No idea. Keep in mind that Nashorn is deprecated since Java-11 and removed since Java15.
I'm unfortunately still on Java 8 :-(. I assume that there is a replacement? Since I'm using final ScriptEngine engine = manager.getEngineByName("javascript");, I assume it will use whatever the current recommended engine is

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.