nanofarad
nanofarad

Reputation: 41281

Instantiating an abstract class in Rhino interpreter in Java Scripting

I am using javax.script.* with Rhino for scripting in a Java program.

A script can implement an interface just fine, but when I try to use similar syntax to instantiate an abstract class(giving the definitions for the unimplemented methods) I get an error saying that MyTestAbstractClass(the class I am trying to instantiate) is an interface or abstract. Am I doing something very wrong?

This is the Javascript code I am using:

var testObject  = new foo.mytestpackage.TestAbstractClass() {
    printMessage: function() {
        print("foo");
    }
};

When TestAbstractClass is a class with a normal constructor(no parameters), I get the following stacktrace:

javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException: error instantiating (JavaAdapter: first arg should be interface Class (<Unknown source>#1)): class com.merkle.TestObject is interface or abstract (<Unknown source>#1) in <Unknown source> at line number 1
    at com.sun.script.javascript.RhinoScriptEngine.eval(Unknown Source)
    at com.sun.script.javascript.RhinoScriptEngine.eval(Unknown Source)
    at javax.script.AbstractScriptEngine.eval(Unknown Source)

I'm using Sun's (slightly simplified, as I have heard) Rhino implementation, and using the official Rhino jars is something I'd like to avoid as they're pretty large.

Upvotes: 1

Views: 1283

Answers (1)

McDowell
McDowell

Reputation: 108949

Oracle's release notes for Java 7's JavaScript Engine suggest that instantiating abstract types is not supported:

Rhino's JavaAdapter has been overridden. JavaAdapter is the feature by which Java class can be extended by JavaScript and Java interfaces may be implemented by JavaScript. We have replaced Rhino's JavaAdapter with our own implementation of JavaAdapter. In our implementation, only single Java interface may be implemented by a JavaScript object.

This seems to be borne out by the error message:

JavaAdapter: first arg should be interface Class (<Unknown source>#1)

You'll have to implement the type in Java and consume the implementation if you aren't willing to switch engines.

Upvotes: 2

Related Questions