[英]Casting objects in JRuby
Is there a way I can explicitly cast one Java object to another Java class from JRuby?有没有一种方法可以将一个 Java 对象从 JRuby 显式转换为另一个 Java 类?
Sometimes I want to be able to invoke SomeJavaClass#aMethod(MySuperClass)
rather than SomeJavaClass#aMethod(MyClass)
from JRuby.有时我希望能够从 JRuby 调用SomeJavaClass#aMethod(MySuperClass)
而不是SomeJavaClass#aMethod(MyClass)
。
From Java, I'd do this:从 Java,我会这样做:
someJavaObject.aMethod( (MySuperClass) myObj );
but I didn't see a #cast
ruby method or anything like that to do the equivalent from JRuby.但我没有看到#cast
ruby 方法或类似的方法来执行 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.请注意,问题Casting Java Objects From JRuby缺少一般情况的答案,这就是我重新提出这个问题的原因。
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.您需要使用从 JRuby 1.4 开始可用的#java_send
或#java_alias
功能来选择您希望调用的方法。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.