Search code examples
javanashorn

Extending an abstract SAM class with parameters in Nashorn


I am trying to extend an abstract class in Java using a Javascript function. For example, test/A.java:

package test;

public class A {
    public A(String s) {}

    public abstract void go(Object a);
}

and test.js:

var myA = new Packages.test.A(function f(a) { print('Calling with '+a); }, 'hello');

Evaluating the line above causes the error Can not create new object with constructor test.A with the passed arguments; they do not match any of its method signatures, but the doc seems to suggest that this method is a valid means of instantiating a subclass:

If the abstract class has a single abstract method (a SAM type), then instead of passing a JavaScript object to the constructor, you can pass the function that implements the method. The following example shows how you can simplify the syntax when using a SAM type:

var task = new TimerTask(function() { print("Hello World!") });

Whichever syntax you choose, if you need to invoke a constructor with arguments, you can specify the arguments after the implementation object or function.


Solution

  • The function argument comes last, not first. The documentation is in error and will need to be fixed; I raised an issue for it. Thanks for pointing this out.

    var myA = new Packages.test.A('hello', function f(a) { print('Calling with '+a); });

    should work.