简体   繁体   English

JSR223:从脚本调用Java“ varargs”方法

[英]JSR223: Calling Java “varargs” methods from script

I have a method that looks like this on Java: 我有一个在Java上看起来像这样的方法:

public void myMethod(Object... parms);

But I can't call this method as expected from the scripts. 但是我无法从脚本中按预期方式调用此方法。

If, in ruby, I do: 如果我用红宝石做:

$myObject.myMethod(42);

It gives me org.jruby.exceptions.RaiseException: could not coerce Fixnum to class [Ljava.lang.Object 它给我org.jruby.exceptions.RaiseException: could not coerce Fixnum to class [Ljava.lang.Object

If I try the following in Javascript: 如果我尝试使用Javascript进行以下操作:

myObject.myMethod(42);

Then it gives me sun.org.mozilla.javascript.internal.EvaluatorException: Can't find method MyClass.test(number). (#2) in at line number 2 然后它给了我sun.org.mozilla.javascript.internal.EvaluatorException: Can't find method MyClass.test(number). (#2) in at line number 2 sun.org.mozilla.javascript.internal.EvaluatorException: Can't find method MyClass.test(number). (#2) in at line number 2

Of course, if I change the signature to take one single object then it works. 当然,如果我将签名更改为仅包含一个对象,那么它将起作用。

I assume that this is because someone along the line does not know how to convert, say Integer to Integer[] with the value at the first position. 我认为这是因为沿途有人不知道如何转换,比如说IntegerInteger[]的值在第一个位置。

I believe something like myMethod({42, 2009}) would work in Ruby, but this seems ugly - I wanted to be able to just do myMethod(42, 2009) to make it less confusing, specially for other languages. 我相信像myMethod({42, 2009})可以在Ruby中工作,但是这看起来很丑-我希望能够只使用myMethod(42, 2009)来减少混乱,尤其是对于其他语言。 Is there any better workaround for this? 有没有更好的解决方法呢?

Thanks. 谢谢。

Java internally treats the variable-length argument list as an array whose elements are all of the same type. Java在内部将变长参数列表视为一个数组,其元素都属于同一类型。 That is the reason why you need to provide an array of objects in your JRuby script. 这就是为什么需要在JRuby脚本中提供对象数组的原因。

It works like this: 它是这样的:

myMethod [42, 2009].to_java

The to_java method constructs a Java array from a Ruby array. to_java方法从Ruby数组构造Java数组。 By default, to_java constructs Object arrays as needed in this case. 默认情况下,在这种情况下, to_java根据需要构造Object数组。 If you need a String array you would use 如果您需要一个String数组,则可以使用

["a","b","c"].to_java(:string)

More on this at the JRuby wiki JRuby Wiki上的更多内容

Varargs are handled by the compiler as an Object[] which is what the error message describes. 可变参数由编译器作为Object []处理,这是错误消息所描述的内容。

I do not have JRuby experience, but does it work if you have an array argument? 我没有JRuby经验,但是如果您有数组参数,是否可以使用?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM