【发布时间】:2014-10-25 12:38:02
【问题描述】:
假设以下 API:
package nashorn.test;
public class API {
public static void test(String string) {
throw new RuntimeException("Don't call this");
}
public static void test(Integer... args) {
System.out.println("OK");
}
}
以下 Nashorn JavaScript sn-p 将失败:
var API = Java.type("nashorn.test.API");
API.test(1);
第一个方法将被调用而不是第二个。这是 Nashorn 引擎中的错误吗?
For the record, this issue was previously reported on the jOOQ User Group,其中方法重载和可变参数被大量使用,这个问题可能会带来很多麻烦。
关于拳击
可能有人怀疑这可能与拳击有关。它没有。当我这样做时也会出现问题
public class API {
public static void test(String string) {
throw new RuntimeException("Don't call this");
}
public static void test(Integer... args) {
System.out.println("OK");
}
public static void test(MyType... args) {
System.out.println("OK");
}
}
还有:
public class MyType {
}
然后:
var API = Java.type("nashorn.test.API");
var MyType = Java.type("nashorn.test.MyType");
API.test(new MyType());
【问题讨论】:
-
由于可变参数是数组的语法糖,我认为 Nashorn 做了正确的事情。
-
@zeroflagL:但我什至不使用字符串调用该方法。不涉及字符串类型!如果这是一个模棱两可的情况,我宁愿抛出异常而不是调用“错误”(即意外)方法
-
你调用一个带有一个参数的方法,它不是一个数组。
API有一个带有单个非数组/非可变参数的方法。匹配。来自文档:如果 Java 方法需要 String 或 Boolean 对象,则将使用 JavaScript 规范定义的 ToString 和 ToBoolean 转换允许的所有转换来转换值。虽然我理解你的立场,但对我来说这似乎是一种合理的行为。 -
@zeroflagL: If you mean this documentation 我只想说没有指定可变参数的情况,至少没有在我们期望 JLS 的粒度级别上......但是@987654323 @,我现在可以从 JavaScript 开发人员的角度看到这种行为的意义。
标签: java javascript java-8 nashorn