我正在尝试使用 Javascript 函数扩展 Java 中的抽象类。例如,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');
评估上面的行会导致错误无法使用传递的参数使用构造函数 test.A 创建新对象;它们不匹配其任何方法签名
,但doc似乎表明此方法是实例化子类的有效方法:
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('用 '+a 调用); });
应该可以。
关于java - 使用 Nashorn 中的参数扩展抽象 SAM 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34861880/