Callbacks in JSR223 Javascript, difference between Oracle JRE 1.6 and OpenJDK 1.6 (as installed, for example, Debian)

Given the following, working with Oracle JRE 6 gives boo output, but OpenJDK 6 gives an exception

javax.script.ScriptException: sun.org.mozilla.javascript.EvaluatorException: The choice of Java constructor replace matching JavaScript argument types (function,string) is ambiguous; candidate constructors are: class java.lang.String replace(char,char) class java.lang.String replace(java.lang.CharSequence,java.lang.CharSequence) (<Unknown source>#1) in <Unknown source> at line number 1 

This is presumably because with OpenJDK (presumably the rt.jar supplied with it) the function gets java.lang.String , but with Oracle it gets a JavaScript string (or something that can be implicitly forced to one).

So what is more true? Javascript (in this case) is an API, so can we write Java so that the API is the same for any implementation? (If the OpenJDK implementation is โ€œmore correctโ€ (and most likely will be the way everyone will do in the future), then I assume that the API change (documentation, examples, tests) by throwing in a new String(...) , as needed it would be impossible, but I would prefer not to guess the API if I'm not sure.)

 import javax.script.*; class st { public static void main(String[] args) { ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine jsEngine = mgr.getEngineByName("JavaScript"); Bindings bindings = jsEngine.getBindings(ScriptContext.ENGINE_SCOPE); Foo foo = new Foo(); bindings.put("v", foo); try { jsEngine.eval("v.run(function(a) {println(a.replace(/f/,\"b\"));})"); } catch (ScriptException ex) { ex.printStackTrace(); } } } 

and

 public class Foo { public void run(FooCB cb) { cb.run("foo"); } public static interface FooCB { public void run(Object val); } } 
+3
source share
1 answer

The Java SE 6 specification ( JSR 270 ) simply says:

There will be no requirement that a particular scripting language is supported by the platform; developers can choose to include support for the scripting language (s) of their choice, as they see fit.

As far as I know, there is no formal specification of how to integrate Java types into JavaScript. This is sad, but there is no reason to expect 100% compatibility between implementations.

I believe that both Oracle JRE and OpenJDK ship with Rhino, but there are no guarantees regarding version level, patches, etc.

+3
source

All Articles