I’ve just finished adding part of the Java Integration proposal, the
“java_send” and “java_method” methods. This is likely the only part of
the “grand unified theory of Java integration” that will get into 1.4,
so I wanted to give a few quick examples.
The “java_send” method is for calling an overloaded or
unfortunately-named Java method from Ruby when all other mechanisms
fail. Here’s a couple examples:
import java.util.ArrayList
list = ArrayList.new
list.java_send :add, [Java::int, java.lang.Object], 0, ‘foo’
puts list.java_send :toString # => “[foo]”
This works for all instance methods. I have not implemented it for
static methods…does it seem like I should?
Now it’s likely that java_send will be slower than you want in some
cases. It’s going to dig into reflection, find the right method, wrap
it in appropriate clothes, and invoke it. But you may want to save the
object it finds and dispatch directly yourself. That’s where
java_method comes in.
With the “java_method” method you can get a reference to any
overloaded Java method as a Ruby Method or UnboundMethod object:
get a bound Method based on the add(int, Object) method from ArrayList
add = list.java_method :add, [Java::int, java.lang.Object]
add.call(0, ‘foo’)
get an UnboundMethod from the ArrayList class:
toString = ArrayList.java_method :toString
toString.bind(list).call # => [foo, foo]
get a bound Method for a static method on either an instance or a
class
JInteger = java.lang.Integer
valueOf = JInteger.java_method :valueOf, [Java::int]
valueOf.call(1) # => a new java.lang.Integer object for value 1
valueOf = JInteger.new(1).java_method :valueOf, [Java::int]
etc
Note that either mechanism should allow you to call the “int”
overloads of a “long” method when that’s really what you need to do.
These should provide workarounds for almost all cases where JRuby
selects the wrong overload, and you should hopefully never have to dig
into the JavaClass/JavaObject/JavaMethod subsystem again.
Both of these have specs in spec/java_integration/methods, and I’m
open to suggestions for improvement.
- Charlie
To unsubscribe from this list, please visit:
http://xircles.codehaus.org/manage_email