JRuby Cookbook

From JRubyWiki

Jump to: navigation, search

Contents

JRuby DateTime

In (J)Ruby, a specific time on a certain day can be represented, differently, using either DateTime or Time.

To convert between instances of these two (J)Ruby classes, see Converting between Time and DateTime.

As of JRuby 0.92, the following code runs but doesn't do what you expect:

java.text.DateFormat.getDateInstance().format(Time.now) // Ruby time in seconds, Java.util.Date in milliseconds

Trying

java.text.DateFormat.getDateInstance().format(DateTime.now) // FAIL

does not work either, as JRuby does not convert from a DateTime to a Java.util.Date object for you.

Creating Java Arrays

You can convert ruby arrays to java arrays very simply:

[1,2,3].to_java => makes an object array
[1,2,3].to_java :byte => makes a byte array
[1,2,3].to_java :String => makes a String array

To create empty arrays:

Java::byte[12].new => makes a new byte[]
java.lang.String[12].new => makes a new String[]

Adding Methods To Java Interfaces

Ruby classes are always open, and so (on the jruby side) are java classes. So this works:

class ArrayList
  def foo; "Hello!"; end
end
ArrayList.new.foo => "Hello!"

However this isn't very useful since we often only know the interface involved (e.g. SQL ResultSets). The following will add methods to interfaces:

JavaUtilities.extend_proxy("java.util.List") do
  def bar; "Goodbye!"; end
end
ArrayList.new.bar => "Goodbye!"


Using Java Serialization and Deserialization

Java serialization (via ObjectOutputStream) works as you'd expect. However, in order to deserialize objects, it is necessary to play games with classloaders:

class JRubyOIS < ObjectInputStream
  def resolveClass(object_stream_class)
    java.lang.Class.forName(object_stream_class.name, true,JRuby.runtime.getJRubyClassLoader)
  end
end
Personal tools