views:

346

answers:

3

Hello,

I have a method that looks like this on 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

If I try the following in 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

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.

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. Is there any better workaround for this?

Thanks.

A: 

Varargs are handled by the compiler as an Object[] which is what the error message describes.

I do not have JRuby experience, but does it work if you have an array argument?

Thorbjørn Ravn Andersen
+2  A: 

Java internally treats the variable-length argument list as an array whose elements are all of the same type. That is the reason why you need to provide an array of objects in your JRuby script.

It works like this:

myMethod [42, 2009].to_java

The to_java method constructs a Java array from a Ruby array. By default, to_java constructs Object arrays as needed in this case. If you need a String array you would use

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

More on this at the JRuby wiki

MartinGross
another example: jruby -rjava -e 'fmt = java.util.Formatter.new(); puts fmt.format("|%4s|", ["üü"].to_java)'
reto