JRuby: Java and Ruby Together at Last
Using Java Classes in JRuby (Name Clashes Included)
Now that you have run a sample, take a look at ways that JRuby allows Ruby programs to use Java classes. The most important method that JRuby provides is the Kernel#include_class method. This method is used to allow Ruby to use that Java class as is:
require "java" # Include Java's FileReader include_class "java.io.FileReader" filename = "./samples/java2.rb" fr = FileReader.new filename
However, there can be name clashes between Java class names and Ruby class names. String is an example of this; Java has java.util.String and Ruby also has Kernel::String. To resolve this name clash, you can rename the class while including it by passing a code block to the include_class method call:
require "java" # Include Java's String as JString include_class("java.lang.String") { |package, name| "J" + name } s = JString.new("Hello World from JRuby!") puts s
require "java" module JavaLang include_package "java.lang" end s = JavaLang::String.new("Hello World from JRuby!") puts s
Here is a sample program, javaHello.rb, that uses Java's HashMap to store three strings and print them out. The interesting thing about this program is the fact that it invokes the the Ruby 'each' method on the java.util.Set returned by the java.util.HashMap.keySet() method call. This allows the resulting keys returned by the 'each' method to be passed to the code block, which gets the String stored with that key, and print that String.
require "java" module JavaLang include_package "java.lang" end include_class("java.util.HashMap") { |pkg, name| "J" + name } s = JavaLang::StringBuffer.new("Hello Java World") puts s.append(", I love JRuby") m = JHashMap.new() m.put("java", "Java") m.put("ruby", "Ruby") m.put("jruby", "JRuby") puts m m.keySet().each { |key| puts m.get(key) }
Here is the output when it is run with JRuby:
C:\JRuby>jruby javaHello.rb Hello Java World, I love JRuby {java=Java, ruby=Ruby, jruby=JRuby} Java Ruby JRuby C:\JRuby>
A similar program written entirely in Java would look like this:
StringBuffer s = new StringBuffer("Hello Java World"); s.append(", I love JRuby"); HashMap<String> m = new HashMap<String>(); m.put("java", "Java") m.put("ruby", "Ruby") m.put("jruby", "JRuby") for (String key: m.keySet()) { println(m.get(key)); }
Page 2 of 3