February 17, 2019
Hot Topics:

JRuby: Java and Ruby Together at Last

  • October 26, 2006
  • By Dominic Da Silva
  • Send Email »
  • More Articles »

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

By defining a Ruby module that includes the Java class definitions, you also can avoid this name clash:

require "java"
module JavaLang
   include_package "java.lang"

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"

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}


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()) {

Page 2 of 3

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date