javacastingjrubyjruby-java-interop

Casting objects in JRuby


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.


Solution

  • 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