在 Nashorn 中使用参数扩展抽象 SAM class

Extending an abstract SAM class with parameters in Nashorn

我正在尝试使用 Java 脚本函数扩展 Java 中的抽象 class。例如,test/A.java:

package test;

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

    public abstract void go(Object a);
}

test.js

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

评估上面的行会导致错误 Can not create new object with constructor test.A with the passed arguments; they do not match any of its method signatures,但 doc 似乎表明此方法是实例化子 class:

的有效方法

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.

函数参数在最后,而不是在前面。文档有误,需要修复;我为此筹集了an issue。感谢您指出这一点。

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

应该可以。