Binding a Java Integer to JavaScriptEngine doesn't work

Posted by rplantiko on Stack Overflow See other posts from Stack Overflow or by rplantiko
Published on 2011-06-24T07:30:20Z Indexed on 2011/06/24 8:22 UTC
Read the original article Hit count: 263

Filed under:
|
|

To see how binding Java objects to symbols in a dynamic language works, I wrote the following spike test, binding a java.lang.Integer to the symbol i to be changed in JavaScript:

  @Test 
  public void bindToLocalVariable() throws ScriptException {

    javax.script.ScriptEngineManager sem 
       = new javax.script.ScriptEngineManager();
    javax.script.ScriptEngine engine 
       = sem.getEngineByName("JavaScript");    

    Integer i = new Integer(17);

    engine.put( "i", i );        
    engine.eval( "i++;" );  // Now execute JavaScript

    assertEquals( 18, i.intValue() );        

    }

Unfortunately, I get a failure.

java.lang.AssertionError: expected:<18> but was:<17>

JavaScript knows the symbol i (otherwise it would have thrown a ScriptException which is not the case), but the increment operation i++ is not performed on the original Integer object.

Any explanations?

© Stack Overflow or respective owner

Related posts about java

Related posts about JavaScript