0

I'm using java 6 javax.script feature but I have an issue :

Before I call the ScriptEngine.eval() method I put some attributes to the ScriptContext:

scriptContext.setAttribute("Utils", utils, ScriptContext.ENGINE_SCOPE);

In the script I call :

var s = utils.getMyString()

The Java getMyString() method returns a String (java.lang.String).

The type of 's' in the scriptContext is sun.org.mozilla.javascript.internal.NativeJavaObject that wrap the Java String instance.

When I try to get the attribute from the context in Java with:

(String) scriptContext.getAttribute("s");

I got

    java.lang.ClassCastException:
 sun.org.mozilla.javascript.internal.NativeJavaObject cannot be cast to java.lang.String

When I write in the script:

var s = "hello world"

or

var s = "" + utils.getMyString()

or

var s = String(utils.getMyString())

all is well because these are javascript Strings that can be get from the scriptContext thanks to an internal conversion.

I think that NativeJavaObjects should be unwrapped (see sun.org.mozilla.javascript.internal.Wrapper.unwrap()) when they are released from the scriptContext.

So, is it a bug ? I have the same issue with java7u5.

I don't beleive that I would have to do :

var s = String(utils.getMyString())

to convert a Java String to a JavaScript String to be able to get it back as a Java String...

Thanks for your point of view.

1
  • The problem occurs for Strings. If getMyString() returns MyString instance It works. So why this issue for methods returning Strings ??? Commented Jul 18, 2012 at 13:38

1 Answer 1

1

The problem seems to be similar to: https://stackoverflow.com/questions/11814010/javascript-rhino-java-float-method-returns-number-or-object and Rhino Javascript: How to convert Object to a Javascript primitive?

but in your case I beleive that:

Context.enter().getWrapFactory().setJavaPrimitiveWrap(false); 

will throw NullPointerException. You use Rhino from JDK javax.script, and ScriptEngine.eval methods wrapps all operations handling context (enter, exit context etc), so if you invoke above-mentioned code before eval, rhino context may not be initialized (enter method assign context to current Thread).

Solution may be to use Rhino directly form org.mozilla and handling context directly: link and invoke above code when enter a context.

I had similar problem (and others as well) when i used JDKs ScriptEngine and i solved it using Rhino form mozilla.

Sign up to request clarification or add additional context in comments.

Comments

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.