a = java.util.ArrayList
alias :size_original :size
puts "calling size method"
As simple as that, you could redefine methods in your Java code. It’s not always good practice to monkeypatch, as inheritance is as effective, but in case of one-off scripts, it could be the way to go.
Last night I wrote a Java class that performs a checkout from a SVN repository. I was able to integrate it with Groovy really fast, and was wondering how fast I could get it going with JRuby. I started to do some research on google, I downloaded the JRuby binary from http://dist.codehaus.org/jruby/, and I fired up jirb to do some quick testing.
Before I get to the JRuby part, let me add a little bit of information about the class I wanted to run: the only method I was interested to run was main, because most of the information was hardcoded in it.
So, I imported Java’s String class, hoping to build an array I could pass to main.
java_import "java.lang.String" do |package,classname|
This imports Java’s String class under the name JString, because Ruby has a String class as well. To create a JString object, you use Ruby’s regular object creation syntax :
Ok, so after I imported the java.lang.String class, I created an array of them:
java_import "java.lang.String" do |pk,nm|
args = [JString.new("first_arg"),JString.new("second_arg")]
Notice I imported the SCli class as well. That is my Java class. In order for the import to work, you should place the class in the CLASSPATH variable, or add the class file to your JRuby project’s lib folder and add that folder to the CLASSPATH. Also, if your class is inside a package, you should add that to the java_import line. Mine wasn’t in one.
Running this script gave me the following error :
main.rb:9: for method main expected [#<Java::JavaClass:0x9d5793>]; got: [org.jruby.RubyArray]; error: argument type mismatch (TypeError)
I was kind of hoping the array would pass for a Java array 🙂 . So, I started to search after this error message, and I got to the Calling Java from JRuby page. After a little bit of reading, I got it to work using the following script :