12

Is there a way I can explicitly cast one Java object to another Java class from JRuby?

Sometimes I want to be able to invoke SomeJavaClass#aMethod(MySuperClass) rather than SomeJavaClass#aMethod(MyClass) from JRuby.

From Java, I'd do this:

someJavaObject.aMethod( (MySuperClass) myObj );

but I didn't see a #cast ruby method or anything like that to do the equivalent from JRuby.

Note that the question Casting Java Objects From JRuby lacks an answer for the general case, which is why I'm re-asking the question.

1 Answer 1

11

You need to make use of either the #java_send or #java_alias feature available starting with JRuby 1.4 to select the method you wish to call. Example:

class Java::JavaUtil::Arrays
  boolean_array_class = [false].to_java(:boolean).java_class
  java_alias :boolean_equals, :equals, [boolean_array_class, boolean_array_class]
end

a1 = [false, true]
Java::JavaUtil::Arrays.boolean_equals a1, a1
# => TypeError: for method Arrays.equals expected [class [Z, class [Z]; got: [org.jruby.RubyArray,org.jruby.RubyArray]; error: argument type mismatch
Java::JavaUtil::Arrays.boolean_equals a1.to_java(:boolean), a1.to_java(:boolean)
# => true
a2 = [true, false]
Java::JavaUtil::Arrays.boolean_equals a1.to_java(:boolean), a2.to_java(:boolean)
# => false
Sign up to request clarification or add additional context in comments.

1 Comment

I think it would be useful to add that if you're trying to cast to non-primitive classes, you should use the full hierarchy. So, say, to to cast obj to ij.text.TextWindow class, you'd have to write obj.to_java(Java::Ij::text::TextWindow).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.