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|
"J#{classname}"
end
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 :
JString.new("whatever")
Ok, so after I imported the java.lang.String class, I created an array of them:
args = [JString.new("argument"),JString.new("otherArgument")]
And I passed it to the class’s main method :
require "java"
java_import "java.lang.String" do |pk,nm|
"J#{nm}"
end
java_import "SCli"
args = [JString.new("first_arg"),JString.new("second_arg")]
SCli.main(args)
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 :
require "java"
java_import "SCli"
args = ["arg1","arg2"].to_java(:string)
SCli.main(args)
Nice,right?
Nice! Useful tip. Thx.
You may like to import Java’s String like this instead:
JString = java.lang.String
And yes, your ultimate to_java(:string) is the recommended way…kudos!
Thanks for the tip Charlie!