Skip to content
banshee edited this page Sep 21, 2011 · 12 revisions
require 'path/to/file.jar'
require can take a path to a jar file. It searches the JRuby $LOAD_PATH for the file.
require 'java'
A special `require 'java'` directive in your file will give you access to any bundled Java libraries (classes within your java class path). However, this will not give you access to any non-bundled libraries.
#each
JRuby supports calling the `#each` method on Enumerable objects
Name translations
Java: org.foo.department.Widget
Ruby: Java::OrgFooDepartment::Widget

For the top-level Java packages java, javax, org, and com you can type in a fully qualified class name:

java_import java.lang.System

You can use your own top-level package names by adding a def:

def edu
  Java::Edu
end

java_import edu.example.MyClass
Importing a package into a class or module
module M
 include_package "org.xxx.yyy"
 # now any class within "org.xxx.yyy" will be available within
 # this module, ex if "org.xxx.yyy.MyClass" exists
 # a = MyClass.new
end
Note that there are issues with include_package, discussed at http://jira.codehaus.org/browse/JRUBY-5558.
enums
Available as constants:
ms_constant_value = java.util.concurrent.TimeUnit::MILLISECONDS
Alternative Names and Beans Convention
You can use underscore-separated names in addition to camel-cased names. These two call the same method:
java.lang.System.currentTimeMillis
java.lang.System.current_time_millis

JRuby also translates methods following the 'beans-convention':

x.getSomething            becomes   x.something
x.setSomething(newValue)  becomes   x.something = new_value
x.isSomething             becomes   x.something?
Constructors
JavaClass.new or JavaClass.new(x,y,z) generally work as expected. If you wish to select a particular constructor by signature use reflection:
 # Get the the three-integer constructor for this class
 construct = JavaClass.java_class.constructor(Java::int, Java::int, Java::int)
 # Use the constructor
 object = cons.new_instance(0xa4, 0x00, 0x00)

Clone this wiki locally