sun.org.mozilla Rhino and extending Java abstract classes
Asked Answered
R

1

5

In the sun.org.mozilla version of Rhino, JavaAdapter only takes interfaces as its first argument instead of any other kind of class according to this error message:

javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorExcep
tion: JavaAdapter: first arg should be interface Class (<Unknown source>#11) in
<Unknown source> at line number 11

Is there any way, no matter how hacky, to extend an abstract class (or a normal class for that matter) via Rhino?

Here is the offending code:

var j = new JavaAdapter(foo.bar.abstractClass, {
    field : "test",
    method : function () {
        print("on enable");
    }
});
Ruffina answered 26/1, 2011 at 2:50 Comment(2)
It would help if you posted the code that caused that error and the stacktrace.Freeboot
i added the offending code per your suggestion.Ruffina
F
7

The other answer is correct for the Sun version of Rhino. It's not entirely clear from the phrasing of the question if switching to the original (Mozilla) Rhino is an option for you or not.

Specifically, when Sun added Rhino to Java, "a few components have been excluded due to footprint and security reasons", and one of them was Mozilla's JavaAdapter. Sun wrote their own "JavaAdapter" but it is much smaller and simpler than the Mozilla one, and it can only be used to implement a single Java interface. Mozilla's original JavaAdapter has no such restriction: I use it to implement abstract classes all the time.

It has nothing to do with some vague philosophical difference like "JavaScript isn't actually 'OO' in the same way as Java". Sun thought that "The uses of JavaAdapter to extend a Java class or to implement multiple interfaces are very rare" (ibid) and decided to remove this feature.

If it's acceptable to ship an 850KB jar file with your code, then grab Mozilla Rhino and implement all the abstract classes you want!

Fill answered 17/7, 2011 at 2:25 Comment(1)
It is more acceptable to ship a 850KB jar than to not ship the feature at all!Ruffina

© 2022 - 2024 — McMap. All rights reserved.