java - 使用 Nashorn 中的参数扩展抽象 SAM 类

标签 java nashorn

我正在尝试使用 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/

相关文章:

javascript - 使用 Nashorn 将 JavaScript 文件添加到 Maven 类路径

javascript - Java 8 Nashorn 空白问题

java - Spring中Service层的作用是什么?在这种情况下我如何拆分我的逻辑?

java - JAVA:Need Server Side Cookie Creator(已关闭服务器)

java - 基本扑克程序 - 打印牌组

java - 从 Nashorn 脚本中对 Java 对象设置 "Callable"

java - 在 Nashorn 中使用重载方法实现 java 类型

java - 在 Koloboke 集之间复制时出现性能问题

java - 如何使用 qtj 和 java 从一组图像创建电影?

javascript - 在 Java 中映射 JSON 对象