<?xml version="1.0" encoding="UTF-8"?>
<page>
  <created-at type="datetime">2008-08-12T00:42:34Z</created-at>
  <description>Added a section on catching and throwing Java exceptions in Ruby.</description>
  <id type="integer">131</id>
  <name>CallingJavaFromJRuby</name>
  <number type="integer">20</number>
  <person-id type="integer">33925</person-id>
  <text>[[Home|&amp;raquo; JRuby Project Wiki Home Page]]
&lt;h1&gt;Scripting Java from JRuby&lt;/h1&gt;
__TOC__
== An example ==

As of JRuby 1.0, a special &lt;tt&gt;require&lt;/tt&gt; &lt;tt&gt;'java'&lt;/tt&gt; directive in your file will give you access to the bundled Java libraries. However, this will ''not'' give you access to non-bundled libraries. A bit more is needed for that, which will be discussed later.

All the following examples can be tested using '''jirb_swing''', the Swing-based IRB console that comes with JRuby.

The following code shows this. Unless it was messed up while adding wiki tags, it should pop up a small window showing &quot;Hello&quot; on your screen.
&lt;pre name=&quot;ruby&quot;&gt;
    # Valid as of JRuby 1.0
    
    # This is the 'magical Java require line'.
    require 'java'
    
    # With the 'require' above, we can now refer to things that are part of the
    # standard Java platform via their full paths.
    frame = javax.swing.JFrame.new(&quot;Window&quot;) # Creating a Java JFrame
    label = javax.swing.JLabel.new(&quot;Hello&quot;)
    
    # We can transparently call Java methods on Java objects, just as if they were defined in Ruby.
    frame.getContentPane.add(label)  # Invoking the Java method 'getContentPane'.
    frame.setDefaultCloseOperation(javax.swing.JFrame::EXIT_ON_CLOSE)
    frame.pack
    frame.setVisible(true)
&lt;/pre&gt;

'''Note:''' If you are testing the example above in the Swing IRB console '''jirb_swing''', change the default close operation to DISPOSE_ON_CLOSE, or HIDE_ON_CLOSE unless you want '''jirb_swing''' to also close when you close the second window.

Here's another example (showing results from testing these statements in the '''jirb''' console). 

Let's say you wanted to get a list of network interfaces. You can get Java API docs at &lt;tt&gt;[http://java.sun.com/j2se/1.5.0/docs/api/index.html/ java.net.NetworkInterface]&lt;/tt&gt;. 

Here's how to access the methods from this Java Class from from JRuby:

  irb(main):013:0&gt; ni = java.net.NetworkInterface.networkInterfaces
  =&gt; #&lt;#&lt;Class:01x7e666f&gt;:0x855a27 @java_object=java.net.NetworkInterface$1@821453&gt;

'''&lt;tt&gt;ni&lt;/tt&gt;''' is a Ruby variable holding a Java Enumeration of NetworkInterfaces. You can see the Class ancestry for &lt;tt&gt;ni&lt;/tt&gt; like this:

  irb(main):029:0&gt; ni.class.ancestors
  =&gt; [#&lt;Class:01x7e666f&gt;, Java::JavaUtil::Enumeration, Enumerable, Java::JavaLang::Object, 
  ConcreteJavaProxy, JavaProxy, JavaProxyMethods, Object, Java, Kernel]

Enumeration elements can't be accessed using Array#[] syntax but they do appear as Arrays for many other purposes. You can find out both the Java and Ruby methods for an Enumeration of NetworkInterfaces like this:

  irb(main):032:0&gt; java.net.NetworkInterface.networkInterfaces.methods
  =&gt; [&quot;__jsend!&quot;, &quot;has_more_elements&quot;, &quot;hasMoreElements&quot;, &quot;next_element&quot;, &quot;nextElement&quot;,
  &quot;each&quot;, &quot;reject&quot;, &quot;member?&quot;, &quot;grep&quot;, &quot;include?&quot;, &quot;min&quot;, &quot;sort&quot;, &quot;any?&quot;, &quot;partition&quot;, 
  &quot;each_with_index&quot;, &quot;collect&quot;, &quot;find_all&quot;, &quot;to_a&quot;,  &quot;inject&quot;, &quot;detect&quot;, &quot;map&quot;, &quot;zip&quot;, 
  &quot;sort_by&quot;, &quot;max&quot;, &quot;entries&quot;, &quot;all?&quot;, &quot;find&quot;, &quot;select&quot;, &quot;hashCode&quot;, &quot;notifyAll&quot;, 
  &quot;getClass&quot;, &quot;to_string&quot;, &quot;toString&quot;, &quot;get_class&quot;, &quot;notify_all&quot;, &quot;equals&quot;, 
  &quot;hash_code&quot;, &quot;wait&quot;, &quot;notify&quot;, &quot;__jcreate!&quot;, &quot;java_class&quot;, &quot;eql?&quot;, &quot;synchronized&quot;, 
  &quot;to_java_object&quot;, &quot;equal?&quot;, &quot;java_object&quot;, &quot;java_object=&quot;, &quot;to_s&quot;, &quot;==&quot;, &quot;hash&quot;,
  &quot;java_kind_of?&quot;, &quot;handle_different_imports&quot;, &quot;include_class&quot;, &quot;display&quot;, 
  &quot;object_id&quot;, &quot;frozen?&quot;, &quot;org&quot;, &quot;__id__&quot;, &quot;clone&quot;, &quot;__send__&quot;, &quot;id&quot;, &quot;__jtrap&quot;, 
  &quot;instance_eval&quot;,  &quot;singleton_methods&quot;, &quot;is_a?&quot;, &quot;extend&quot;, 
  &quot;instance_variable_set&quot;, &quot;freeze&quot;, &quot;remove_instance_variable&quot;, &quot;=~&quot;,
  &quot;private_methods&quot;, &quot;methods&quot;, &quot;instance_variable_get&quot;, &quot;nil?&quot;, &quot;send&quot;, 
  &quot;untaint&quot;, &quot;com&quot;, &quot;type&quot;, &quot;class&quot;, &quot;===&quot;, &quot;instance_of?&quot;, 
  &quot;protected_methods&quot;, &quot;tainted?&quot;, &quot;kind_of?&quot;, &quot;javax&quot;, &quot;inspect&quot;, &quot;java&quot;, 
  &quot;instance_exec&quot;, &quot;taint&quot;, &quot;dup&quot;, &quot;public_methods&quot;, &quot;instance_variable_defined?&quot;, 
   &quot;respond_to?&quot;, &quot;method&quot;, &quot;instance_variables&quot;]

Because JRuby supports the &lt;tt&gt;#each&lt;/tt&gt; method on Java Enumerations you can do this:

  irb(main):011:0&gt; java.net.NetworkInterface.networkInterfaces.each {|i| puts i; puts }
  name:en1 (en1) index: 5 addresses:
  /63.138.152.170;
  /fe80:0:0:0:21b:63ff:febf:4a9d%5;
  
  name:en0 (en0) index: 4 addresses:
  /63.138.152.125;
  /fe80:0:0:0:21b:63ff:fe1e:b2da%4;
  
  name:lo0 (lo0) index: 1 addresses:
  /127.0.0.1;
  /fe80:0:0:0:0:0:0:1%1;
  /0:0:0:0:0:0:0:1%0;

== Accessing and Importing Java Classes ==

=== Require a jar file to make resources in the jar discoverable within JRuby ===
To use resources within a jar file from JRuby, the jar file must either be on the classpath or be made available with the &lt;tt&gt;require&lt;/tt&gt; method:

  require 'path/to/mycode.jar'

This &lt;tt&gt;require&lt;/tt&gt; makes the resources in &lt;tt&gt;mycode.jar&lt;/tt&gt; discoverable by commands like &lt;tt&gt;import&lt;/tt&gt; and &lt;tt&gt;include_package&lt;/tt&gt;.

Note that loading jar-files via &lt;tt&gt;require&lt;/tt&gt; searches along the RUBYLIB path, like normal ruby files.

=== Naming a Java Class ===
You can name a Java class in JRuby in at least three different ways. The idea is to map Java names like &lt;tt&gt;org.foo.department.Widget&lt;/tt&gt; to Ruby nested modules. This works as follows:

   Java: org.foo.department.Widget
   Ruby: Java::OrgFooDepartment::Widget

That is:

* Java packages reside in the &lt;tt&gt;Java&lt;/tt&gt; module.
* The package path is transformed by removing the dots and converting to ''CamelCase''

This also means that, just as in Java, packages are not nested.

* For the top-level Java packages &lt;tt&gt;java&lt;/tt&gt;, &lt;tt&gt;javax&lt;/tt&gt;, &lt;tt&gt;org&lt;/tt&gt;, and &lt;tt&gt;com&lt;/tt&gt; you can type in a fully qualified class name basically as in Java, for example, &lt;tt&gt;java.lang.System&lt;/tt&gt;.

You can get the same effect for your own top-level packages, as follows. Let's assume that your packages are called &lt;tt&gt;edu.school.department.Class&lt;/tt&gt;. Then, you define

   def edu
      Java::Edu
   end

And you can use the usual Java package names.

As of JRuby-1.1.5, the &lt;tt&gt;import&lt;/tt&gt; statement only works with either Java-style names or strings, but not with the &lt;tt&gt;Java::PackagePath::Class&lt;/tt&gt; variant.

=== Import a Java Class to Use It Without The Full Path Name ===

You can always access any Java class that has been loaded or is in the classpath by specifying its full name. With the &lt;tt&gt;java_import&lt;/tt&gt; statement or &lt;tt&gt;import&lt;/tt&gt; statement, you can make the Java class available only by its name, just as in Java.

'''Example''': import and use the &lt;tt&gt;java.lang.System&lt;/tt&gt; class.

  require 'java'
  java_import java.lang.System
  version = System.getProperties[&quot;java.runtime.version&quot;]

'''Note:''' As noted in [http://jira.codehaus.org/browse/JRUBY-3171 this bug report], &lt;tt&gt;java_import&lt;/tt&gt; is the preferred, and safer, way to import Java classes.

=== Use include_package within a Ruby Module to import a Java Package ===

Use &lt;tt&gt;include_package &quot;package_name&quot;&lt;/tt&gt; in a Ruby Module to support namespaced access to the Java classes in the package. It is also legal to use &lt;tt&gt;import &quot;package_name&quot;&lt;/tt&gt;.

'''Example''': create a Ruby Module called &lt;tt&gt;JavaLang&lt;/tt&gt; that includes the classes in the Java package &lt;tt&gt;java.lang&lt;/tt&gt;.

  module JavaLang
    include_package &quot;java.lang&quot;
    # alternately, use the #import method
    import &quot;java.lang&quot;
  end

Prefix the Class name with &lt;tt&gt;JavaLang::&lt;/tt&gt; to access the included Classes:

  version = JavaLang::System.getProperties[&quot;java.runtime.version&quot;]
  =&gt; &quot;1.5.0_13-b05-237&quot;

  processors = JavaLang::Runtime.getRuntime.availableProcessors
  =&gt; 2

The Java classes in the package will become available in this class/module, unless a constant with the same name as a Java class is already defined.

The use of the Module name to scope access to the imported Java class is also helpful in cases where the Java class has the same name as an existing Ruby class. 

For example if you need to create an instance of a &lt;tt&gt;java.io.File&lt;/tt&gt; object, this code will work:

  import java.io.File
  newfile = File.new(&quot;file.txt&quot;)
  =&gt; #&lt;Java::JavaIo::File:0xdc6f00 @java_object=file.txt&gt;

However you've now redefined the Ruby constant File and can no longer access the Ruby File class. Executing this:

  File.open('README', 'r') {|f| puts f.readline }

Will produce this error:

  NoMethodError: private method `open' called for Java::JavaIo::File:Class

If instead you create a module called &lt;tt&gt;JavaIO&lt;/tt&gt; and include the package in the module definition:

  module JavaIO     
    include_package &quot;java.io&quot;
  end

You can now create a new instance of the Java class File without shadowing the Ruby version of the File class:

  newfile = JavaIO::File.new(&quot;file.txt&quot;)
  =&gt; #&lt;Java::JavaIo::File:0x15619c @java_object=file.txt&gt;

The Ruby File class is still accessible:

  File.open('README', 'r') {|f| puts f.readline }
  JRuby -  A Java implementation of the Ruby language
  =&gt; nil

=== Accessing Java Enumerations ===
Java &lt;tt&gt;enum&lt;/tt&gt;s are accessible from Ruby code as constants:

  lock.try_lock(5000, java.util.concurrent.TimeUnit::MILLISECONDS)

or 

  java_import java.util.concurrent.TimeUnit
  lock.try_lock(5000, TimeUnit::MILLISECONDS)

=== Gotchas ===

JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. This binding takes place in precedence to the classes &quot;method_missing&quot; handling.

If you do not want this behaviour for a specific class, you can undefine it for that class. Here's an example that will execute identically under Ruby and JRuby:

&lt;pre&gt;
# Note: Comment out for Ruby test. Uncomment for JRuby test.
require 'java'

class MethodMissing
  # JRuby: Undefine the standard &quot;automatic&quot; bindings to Java, to avoid any automatic binding.
  undef org, com, java, javax
  
  def method_missing(m, *args)
    puts &quot;method_missing: #{m}.&quot;
    &quot;This is what I return from method missing.&quot;
  end
end

mm = MethodMissing.new
result = mm.org
puts &quot;Result: #{result} Type: #{result.class.name}&quot;
&lt;/pre&gt;

== Calling a Java Method ==

=== Alternative Names and Beans Convention ===

In Ruby, one usually prefers &lt;tt&gt;method_names_like_this&lt;/tt&gt;, while Java traditionally uses &lt;tt&gt;methodNamesLikeThis&lt;/tt&gt;. If you want, you can use Ruby-style method names instead of the Java ones.

For example, these two calls are equivalent

  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?

You don't have to use these alternatives, but they can make the interaction with Java code feel more Ruby-like.

=== Beware of Java generics ===

If a Java class is defined with Java generics, the types are erased during compilation for backwards compatibility. As a result. JRuby will have problems with automatic type conversion. For example, if you have a &lt;tt&gt;Map&lt;String,String&gt;&lt;/tt&gt;, it will be seen as a simple &lt;tt&gt;Map&lt;/tt&gt;, and JRuby will not be able to determine the correct types using reflection.

=== Additional Methods ===

JRuby defines a number of additional methods for Java objects.

* &lt;tt&gt;java_class&lt;/tt&gt; returns the Java class of an object.
* &lt;tt&gt;java_kind_of?&lt;/tt&gt; works like the &lt;tt&gt;instanceof&lt;/tt&gt; operator.
* &lt;tt&gt;java_object&lt;/tt&gt; returns the underlying Java object. This is useful for reflection.
* &lt;tt&gt;java_send&lt;/tt&gt; overrides JRuby's dispatch rules and forces the execution of a named Java method on a Java object. This is useful for Java methods, such as &lt;tt&gt;initialize&lt;/tt&gt;, with names that conflict with built-in Ruby methods. More below. ''Added in JRuby 1.4''
* &lt;tt&gt;java_method&lt;/tt&gt; retrieves a bound or unbound handle for a Java method to avoid the reflection inherent in &lt;tt&gt;java_send&lt;/tt&gt;. More below. ''Added in JRuby 1.4''

=== Calling masked or unreachable Java methods with &lt;tt&gt;java_send&lt;/tt&gt; ===
Sometimes you need to call &lt;tt&gt;initialize&lt;/tt&gt; AFTER the &lt;tt&gt;.new()&lt;/tt&gt; call, for example the &lt;tt&gt;RTPManager&lt;/tt&gt; class in JMF. Unfortunately, this method is masked by Ruby's &lt;tt&gt;initialize&lt;/tt&gt; constructor method.  As of JRuby 1.4, the &lt;tt&gt;java_send&lt;/tt&gt; method can be used to call this, and any other, masked method:

  @mgr = javax.media.rtp.RTPManager.newInstance
  localhost = java.net.InetAddress.getByName(&quot;127.0.0.1&quot;)
  localaddr = javax.media.rtp.SessionAddress.new(localhost, 21000, localhost, 21001)
  @mgr.java_send :initialize, [javax.media.rtp.SessionAddress], localaddr

In previous versions of JRuby, the same thing can be accomplised with reflection:

  @mgr = javax.media.rtp.RTPManager.newInstance
  localhost = java.net.InetAddress.getByName(&quot;127.0.0.1&quot;)
  localaddr = javax.media.rtp.SessionAddress.new(localhost, 21000, localhost, 21001)
  method = @mgr.java_class.declared_method(:initialize, javax.media.rtp.SessionAddress )
  method.invoke @mgr.java_object, localaddr.java_object

Here is another example of calling the &lt;tt&gt;ArrayList.add&lt;/tt&gt; method with &lt;tt&gt;java_send&lt;/tt&gt;:

 
 import java.util.ArrayList
 list = ArrayList.new
 list.java_send :add, [Java::int, java.lang.Object], 0, 'foo'
 puts list.java_send :toString # =&gt; &quot;[foo]&quot;

Note the second argument, which is an array of types indicating the exact method signature desired. This is useful for disambiguating methods that are overloaded on similar types such as &lt;tt&gt;int&lt;/tt&gt; and &lt;tt&gt;long&lt;/tt&gt;.

=== Bound and Unbound Java methods with &lt;tt&gt;java_method&lt;/tt&gt; ===
&lt;tt&gt;java_send&lt;/tt&gt; relies on reflection and may lead to poor performance in some cases. Each time it is called, the desired method must be relocated. With the &lt;tt&gt;java_method&lt;/tt&gt; method you can get a reference to any overloaded Java method as a Ruby Method object:

 
 # get a bound Method based on the add(int, Object) method from ArrayList
 add = list.java_method :add, [Java::int, java.lang.Object]
 add.call(0, 'foo')
 

Similarly, an Unbound method object can be retrieved:

 # get an UnboundMethod from the ArrayList class:
 toString = ArrayList.java_method :toString
 toString.bind(list).call # =&gt; [foo, foo]

=== Conversion of Types ===

==== Ruby to Java ====

''See the JRuby rspec source code dir'' &lt;tt&gt;spec/java_integration&lt;/tt&gt; ''for many more examples.''

When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:

{| border=&quot;1&quot; style=&quot;text-align:left;&quot; cellspacing=&quot;2&quot; cellpadding=&quot;5&quot; 
|- style=&quot;background:silver&quot;
|'''Ruby Type'''
|'''Java Type'''
|- 
|  &quot;foo&quot; || &lt;tt&gt;java.lang.String&lt;/tt&gt;
|-
| 1 || &lt;tt&gt;java.lang.Long&lt;/tt&gt;
|-
| 1.0 || &lt;tt&gt;java.lang.Double&lt;/tt&gt;
|-
| true, false || &lt;tt&gt;java.lang.Boolean&lt;/tt&gt;
|-
| 1 &lt;&lt; 128 || &lt;tt&gt;java.math.BigInteger&lt;/tt&gt; 
|}

However, this does not mean that you cannot call methods expecting a primitive type. You can also pass an integer to a method expecting a double value. JRuby usually tries quite hard to find a method that can understand your parameters.

If JRuby cannot find a matching method, it tries to pass the actual JRuby objects instead (that is, the Java objects from the JRuby implementation). A consequence of this is that if this fails you will see an error message stating that JRuby hasn't found a method taking an object of class &lt;tt&gt;org.jruby.RubyObject&lt;/tt&gt; instead of the actual type.

If JRuby is not finding the exact method you want to call, perhaps because of extreme ambiguity like &lt;tt&gt;foo(int)&lt;/tt&gt; vs. &lt;tt&gt;foo(long)&lt;/tt&gt;, the &lt;tt&gt;java_send&lt;/tt&gt; method can be used to disambiguate. See below.

==== Java to Ruby ====
When primitive Java types are passed to JRuby they are converted to the following Ruby types:

{| border=&quot;1&quot; style=&quot;text-align:left;&quot; cellspacing=&quot;2&quot; cellpadding=&quot;5&quot; 
|- style=&quot;background:silver&quot;
|'''Java Type'''||'''Ruby Type'''
|- 
| &lt;tt&gt;public String&lt;/tt&gt; || &lt;tt&gt;String&lt;/tt&gt;
|-
| &lt;tt&gt;public byte&lt;/tt&gt; || &lt;tt&gt;Fixnum&lt;/tt&gt;
|-
| &lt;tt&gt;public short&lt;/tt&gt; || &lt;tt&gt;Fixnum&lt;/tt&gt;
|-
| &lt;tt&gt;public char&lt;/tt&gt; || &lt;tt&gt;Fixnum&lt;/tt&gt;
|-
| &lt;tt&gt;public int&lt;/tt&gt; || &lt;tt&gt;Fixnum&lt;/tt&gt;
|-
| &lt;tt&gt;public long&lt;/tt&gt; || &lt;tt&gt;Fixnum&lt;/tt&gt;
|-
| &lt;tt&gt;public float&lt;/tt&gt; || &lt;tt&gt;Float&lt;/tt&gt;
|-
| &lt;tt&gt;public double&lt;/tt&gt; || &lt;tt&gt;Float&lt;/tt&gt;
|}

The Java Booleans true and false are coerced to the Ruby singleton classes TrueClass and FalseClass which are represented in Ruby with the instances true and false.

The null Java object is coerced to the Ruby class NilClass which is represented in Ruby as the instance nil.

==== Java Primitive Classes ====

Java primitive classes can be found in the Java module. For example, &lt;code&gt;Java::byte&lt;/code&gt; represents the primitive type byte in java. You can get its class as follows:

{| border=&quot;1&quot; 
|- style=&quot;background:silver&quot;
|'''Ruby Code''' ||'''Java Class''' 
|- 
| &lt;tt&gt;Java::JavaClass.for_name(&quot;byte&quot;) &lt;/tt&gt; || &lt;tt&gt;Java::byte.java_class&lt;/tt&gt;
|- 
| &lt;tt&gt;Java::JavaClass.for_name(&quot;boolean&quot;) &lt;/tt&gt; || &lt;tt&gt; Java::boolean.java_class&lt;/tt&gt;
|- 
| &lt;tt&gt;Java::JavaClass.for_name(&quot;byte&quot;) &lt;/tt&gt; || &lt;tt&gt; Java::byte.java_class&lt;/tt&gt;
|- 
| &lt;tt&gt;Java::JavaClass.for_name(&quot;short&quot;) &lt;/tt&gt; || &lt;tt&gt; Java::short.java_class&lt;/tt&gt;
|- 
| &lt;tt&gt;Java::JavaClass.for_name(&quot;char&quot;) &lt;/tt&gt; || &lt;tt&gt; Java::char.java_class&lt;/tt&gt;
|- 
| &lt;tt&gt;Java::JavaClass.for_name(&quot;int&quot;) &lt;/tt&gt; || &lt;tt&gt; Java::int.java_class&lt;/tt&gt;
|- 
| &lt;tt&gt;Java::JavaClass.for_name(&quot;long&quot;) &lt;/tt&gt; || &lt;tt&gt; Java::long.java_class&lt;/tt&gt;
|- 
| &lt;tt&gt;Java::JavaClass.for_name(&quot;float&quot;) &lt;/tt&gt; || &lt;tt&gt; Java::float.java_class&lt;/tt&gt;
|- 
| &lt;tt&gt;Java::JavaClass.for_name(&quot;double&quot;) &lt;/tt&gt; || &lt;tt&gt; Java::double.java_class&lt;/tt&gt;
|}

== Arrays ==
There are two ways of constructing Java arrays. One is to use the &lt;code&gt;to_java&lt;/code&gt; method of the class Array. The other is to use the &lt;tt&gt;[]&lt;/tt&gt; method for the primitive Java types.

==== Converting a Ruby Array to a Java Array ====
The &lt;tt&gt;to_java&lt;/tt&gt; method constructs a Java array from a Ruby array:

  [1,2,3].to_java
  =&gt; [Ljava.lang.Object;@1a32ea4

By default, &lt;tt&gt;to_java&lt;/tt&gt; constructs &lt;tt&gt;Object&lt;/tt&gt; arrays. You can specify the parameter with an additional argument which can either be a symbol or a primitive class like &lt;tt&gt;Java::double&lt;/tt&gt;

  [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;].to_java(:string)
  =&gt; [Ljava.lang.String;@170984c

  [1, 2, 3.5].to_java Java::double
  =&gt; [D@9bc984

==== Constructing Empty Java Arrays ====
Sometimes a Java library will need a fixed-length array, say for example a byte buffer for a stream to read into. For this, you can use the &lt;tt&gt;[]&lt;/tt&gt; method of the primitive types in the Java module:

  bytes = Java::byte[1024].new # Equivalent to Java's bytes = new byte[1024];

=== Ruby String to Java Bytes and back again ===
  bytes = 'a string'.to_java_bytes
  =&gt; #&lt;#&lt;Class:01x9fcffd&gt;:0x40e825 @java_object=[B@3d476c&gt;

  string = String.from_java_bytes bytes
  =&gt; &quot;a string&quot;

=== Convert a Java InputStream to a ruby IO object ===

  io = Java.java_to_ruby(org.jruby.RubyIO.new(JRuby.runtime, input_stream).java_object)

[http://logs.jruby.org/jruby/2009-06-23.html#T21-34-32 from ribrdb on irc]
 

== Referencing a &lt;tt&gt;java.lang.Class&lt;/tt&gt; object ==
If you call a Java class from JRuby and need to pass a Java class as an argument, if you use this form:

  DoSomethingWithJavaClass(MyJavaClass.class)

you'll get this error:

  TypeError: expected [java.lang.Class]; 
  got: [org.jruby.RubyClass]; error: argument type mismatch

Instead use the method &lt;tt&gt;java_class&lt;/tt&gt;.

  DoSomethingWithJavaClass(MyJavaClass.java_class)

== Integrating JRuby and Java Classes and Interfaces ==
=== Classes ===
==== Reopening Java Classes ====
In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes.

This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like.

Note that these additions will only be visible on the JRuby side. 

==== Subclassing a Java class ====
You can subclass (i.e. extend) a Java class and then use the JRuby class whenever Java expects the superclass.

==== Gotchas ====
If you have a class name ambiguity between Java and Ruby, the class name will reference the Ruby construct within the Ruby code. For instance, if you import &lt;tt&gt;java.lang.Thread&lt;/tt&gt; and then write &lt;tt&gt;JThread &lt; Thread&lt;/tt&gt;, &lt;tt&gt;JThread&lt;/tt&gt; will in fact inherit the Ruby &lt;tt&gt;Thread&lt;/tt&gt; object, not the Java &lt;tt&gt;Thread&lt;/tt&gt;. The solution is to use the full Java Class name, such as:
 JThread &lt; java.lang.Thread

=== Interfaces ===
Java interfaces are mapped to modules in JRuby. This means that you can also reopen the corresponding module and add further methods on the JRuby side.

==== Implementing Java Interfaces in JRuby ====
JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.

  class SomeJRubyObject
    include java.lang.Runnable
    include java.lang.Comparable
  end

==== Closure conversion ====
JRuby sports a feature called ''closure conversion'', where a Ruby block or closure is converted to an appropriate Java interface. For example:

  button = javax.swing.JButton.new &quot;Press me!&quot;
  button.add_action_listener {|event| event.source.text = &quot;You did it!&quot;}

In this example, the &lt;tt&gt;JButton&lt;/tt&gt;'s &lt;tt&gt;addActionListener&lt;/tt&gt; method takes one parameter, a &lt;tt&gt;java.awt.event.ActionListener&lt;/tt&gt;. The block is converted to a &lt;tt&gt;Proc&lt;/tt&gt; object, which is then decorated with a java interface proxy that invokes the block for any method called on the interface.

This not only works for event listeners or &lt;tt&gt;Runnable&lt;/tt&gt;, but basically for any interface. When calling a method that expects an interface, JRuby checks if a block is passed and automatically converts the block to an object implementing the interface.

 

=== Java classes can't inherit from a JRuby class ===
Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.

== Exception Handling ==
Native Java exceptions can be caught in Ruby code as expected:

 begin
   java.lang.Integer.parse_int(&quot;asdf&quot;)
 rescue java.lang.NumberFormatException =&gt; e
   puts &quot;Failed to parse integer: #{e.message}&quot;
 end

Furthermore, Ruby code can throw Java exceptions:

 begin
   raise java.lang.IllegalArgumentException.new(&quot;Bad param&quot;)
 rescue java.lang.IllegalArgumentException =&gt; e
   puts &quot;Illegal argument: #{e}&quot;
 end

This is useful if you happen to be implementing a Java interface in Ruby that requires a particular exception to be thrown on error.

Note that this can also be written:

 begin
   raise Java::JavaLang::IllegalArgumentException.new(&quot;Bad param&quot;)
 rescue Java::JavaLang::IllegalArgumentException =&gt; e
   puts &quot;Illegal argument: #{e}&quot;
 end

== Synchronization in JRuby ==
When interacting with Java APIs from JRuby, it is occasionally necessary to synchronize on an object for thread safety. In JRuby, a &lt;tt&gt;synchronize&lt;/tt&gt; method is provided on every wrapped Java object to support this functionality. For example, the following Java code:

 
 synchronized(obj) {
     obj.wait(1000); 
 }
 

is implement like this in Ruby:

 
 obj.synchronized do
   obj.wait 1000
 end
 
The expression evaluates to the result of the block, e.g.,

 
 obj.synchronized { 99 }  # =&gt; 99
 

== Material from Before JRuby 1.0 ==
One powerful feature of JRuby is its ability to invoke the classes of the Java Platform. The following example uses JRuby 0.9.2 to create a Java &lt;tt&gt;JFrame&lt;/tt&gt; with a &lt;tt&gt;JLabel&lt;/tt&gt;. 

'''Note:''' Several package paths are magic: &lt;tt&gt;java&lt;/tt&gt;, &lt;tt&gt;javax&lt;/tt&gt;, &lt;tt&gt;org&lt;/tt&gt;, &lt;tt&gt;com&lt;/tt&gt;.  Many package paths will need to be prefixed with &lt;tt&gt;Java&lt;/tt&gt;:

&lt;pre name=&quot;ruby&quot;&gt;
require 'java'

JFrame = javax.swing.JFrame
JLabel = javax.swing.JLabel

frame = JFrame.new()
frame.getContentPane().add(JLabel.new(&quot;This is an example.&quot;))
frame.pack()
frame.setVisible(true)

MyClass = Java::my.package.MyClass
myClass = MyClass.new()
myClass.doit()
&lt;/pre&gt;

'''Note:''' Older versions of JRuby require you to use the following code as the import preamble:

&lt;pre name=&quot;ruby&quot;&gt;
require 'java'

include_class &quot;javax.swing.JFrame&quot;
include_class &quot;javax.swing.JLabel&quot;
&lt;/pre&gt;

JRuby also allows you to call Java code by using the more Ruby-like &lt;tt&gt;underscore_method_naming&lt;/tt&gt; and to refer to JavaBean properties as attributes. The translation rule is that the Java method name is split by capital letters, lowercased, and prepended with &lt;tt&gt;_&lt;/tt&gt;.
&lt;pre name=&quot;ruby&quot;&gt;
frame.content_pane.add(label)
frame.visible = true
&lt;/pre&gt;

JRuby also lets you call Java libraries ''not'' included in the standard set of class libraries associated with the Java Platform. By copying jars to &lt;tt&gt;$JRUBY_HOME/lib&lt;/tt&gt; or by modifying the CLASSPATH environment variable, you can access third-party Java libraries from JRuby scripts or from jirb, an interactive JRuby shell. It is also possible to add a jar to the classpath by requiring the jar (if it exists in the JRuby library load path):
&lt;pre name=&quot;ruby&quot;&gt;
require 'whatever.jar'
com.whatever.Whatever.doSomething
&lt;/pre&gt;

== Related Articles ==
* [http://mikiobraun.blogspot.com/2008/11/java-integration-in-jruby.html Java Integration in JRuby] Short overview article on JRuby and Java integration.
* [http://blogs.sun.com/sundararajan/entry/java_integration_javascript_groovy_and Java Integration: JavaScript, Groovy and JRuby] Side-by-side comparison of Java integration in JavaScript, Groovy and JRuby.
* [http://jruby.codehaus.org/Java+Integration Java Integration] From the JRuby main page.
* [http://jtestr.codehaus.org/ JtestR] A testing framework for Java based on JRuby.
* [http://github.com/leandrosilva/sparrow Sparrow] A JMS client for messaging based on JRuby.


</text>
  <text-as-html>&lt;p&gt;&lt;a href='&lt;?url_for_page Home?&gt;' class='internal'&gt;&amp;raquo; JRuby Project Wiki Home Page&lt;/a&gt;&lt;h1&gt;Scripting Java from JRuby&lt;/h1&gt;&lt;/p&gt;&lt;div id='toc' class='toc'&gt;
           &lt;div id='toctitle' class='toc-title'&gt;
             &lt;span&gt;Contents&lt;/span&gt;
           &lt;/div&gt;
           &lt;div id='toccontents' class='toc-contents'&gt;&lt;ul&gt;&lt;ul&gt;&lt;li&gt;1 &lt;a href='#An_example'&gt; An example &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;2 &lt;a href='#Accessing_and_Importing_Java_Classes'&gt; Accessing and Importing Java Classes &lt;/a&gt;&lt;/li&gt;
&lt;ul&gt;&lt;li&gt;2.1 &lt;a href='#Require_a_jar_file_to_make_resources_in_the_jar_discoverable_within_JRuby'&gt; Require a jar file to make resources in the jar discoverable within JRuby &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;2.2 &lt;a href='#Naming_a_Java_Class'&gt; Naming a Java Class &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;2.3 &lt;a href='#Import_a_Java_Class_to_Use_It_Without_The_Full_Path_Name'&gt; Import a Java Class to Use It Without The Full Path Name &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;2.4 &lt;a href='#Use_include_package_within_a_Ruby_Module_to_import_a_Java_Package'&gt; Use include_package within a Ruby Module to import a Java Package &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;2.5 &lt;a href='#Accessing_Java_Enumerations'&gt; Accessing Java Enumerations &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;2.6 &lt;a href='#Gotchas'&gt; Gotchas &lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;li&gt;3 &lt;a href='#Calling_a_Java_Method'&gt; Calling a Java Method &lt;/a&gt;&lt;/li&gt;
&lt;ul&gt;&lt;li&gt;3.1 &lt;a href='#Alternative_Names_and_Beans_Convention'&gt; Alternative Names and Beans Convention &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;3.2 &lt;a href='#Beware_of_Java_generics'&gt; Beware of Java generics &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;3.3 &lt;a href='#Additional_Methods'&gt; Additional Methods &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;3.4 &lt;a href='#Calling_masked_or_unreachable_Java_methods_with_java_send'&gt; Calling masked or unreachable Java methods with &lt;tt&gt;java_send&lt;/tt&gt; &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;3.5 &lt;a href='#Bound_and_Unbound_Java_methods_with_java_method'&gt; Bound and Unbound Java methods with &lt;tt&gt;java_method&lt;/tt&gt; &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;3.6 &lt;a href='#Conversion_of_Types'&gt; Conversion of Types &lt;/a&gt;&lt;/li&gt;
&lt;ul&gt;&lt;li&gt;3.6.1 &lt;a href='#Ruby_to_Java'&gt; Ruby to Java &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;3.6.2 &lt;a href='#Java_to_Ruby'&gt; Java to Ruby &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;3.6.3 &lt;a href='#Java_Primitive_Classes'&gt; Java Primitive Classes &lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/ul&gt;&lt;li&gt;4 &lt;a href='#Arrays'&gt; Arrays &lt;/a&gt;&lt;/li&gt;
&lt;ul&gt;&lt;ul&gt;&lt;li&gt;4.1 &lt;a href='#Converting_a_Ruby_Array_to_a_Java_Array'&gt; Converting a Ruby Array to a Java Array &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;4.2 &lt;a href='#Constructing_Empty_Java_Arrays'&gt; Constructing Empty Java Arrays &lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;li&gt;4.1 &lt;a href='#Ruby_String_to_Java_Bytes_and_back_again'&gt; Ruby String to Java Bytes and back again &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;4.2 &lt;a href='#Convert_a_Java_InputStream_to_a_ruby_IO_object'&gt; Convert a Java InputStream to a ruby IO object &lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;li&gt;5 &lt;a href='#Referencing_a_java.lang.Class_object'&gt; Referencing a &lt;tt&gt;java.lang.Class&lt;/tt&gt; object &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;6 &lt;a href='#Integrating_JRuby_and_Java_Classes_and_Interfaces'&gt; Integrating JRuby and Java Classes and Interfaces &lt;/a&gt;&lt;/li&gt;
&lt;ul&gt;&lt;li&gt;6.1 &lt;a href='#Classes'&gt; Classes &lt;/a&gt;&lt;/li&gt;
&lt;ul&gt;&lt;li&gt;6.1.1 &lt;a href='#Reopening_Java_Classes'&gt; Reopening Java Classes &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;6.1.2 &lt;a href='#Subclassing_a_Java_class'&gt; Subclassing a Java class &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;6.1.3 &lt;a href='#Gotchas'&gt; Gotchas &lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;li&gt;6.2 &lt;a href='#Interfaces'&gt; Interfaces &lt;/a&gt;&lt;/li&gt;
&lt;ul&gt;&lt;li&gt;6.2.1 &lt;a href='#Implementing_Java_Interfaces_in_JRuby'&gt; Implementing Java Interfaces in JRuby &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;6.2.2 &lt;a href='#Closure_conversion'&gt; Closure conversion &lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;li&gt;6.3 &lt;a href='#Java_classes_can_t_inherit_from_a_JRuby_class'&gt; Java classes can't inherit from a JRuby class &lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;li&gt;7 &lt;a href='#Exception_Handling'&gt; Exception Handling &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;8 &lt;a href='#Synchronization_in_JRuby'&gt; Synchronization in JRuby &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;9 &lt;a href='#Material_from_Before_JRuby_1.0'&gt; Material from Before JRuby 1.0 &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;10 &lt;a href='#Related_Articles'&gt; Related Articles &lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/ul&gt;&lt;/div&gt;
         &lt;/div&gt;&lt;h2&gt;&lt;a name='An_example'&gt;&lt;/a&gt; An example &lt;/h2&gt;
&lt;p&gt;
As of JRuby 1.0, a special &lt;tt&gt;require&lt;/tt&gt; &lt;tt&gt;'java'&lt;/tt&gt; directive in your file will give you access to the bundled Java libraries. However, this will &lt;i&gt;not&lt;/i&gt; give you access to non-bundled libraries. A bit more is needed for that, which will be discussed later.

&lt;/p&gt;&lt;p&gt;All the following examples can be tested using &lt;b&gt;jirb_swing&lt;/b&gt;, the Swing-based IRB console that comes with JRuby.

&lt;/p&gt;&lt;p&gt;The following code shows this. Unless it was messed up while adding wiki tags, it should pop up a small window showing &amp;quot;Hello&amp;quot; on your screen.
&lt;pre name=&quot;code&quot; class=&quot;ruby&quot;&gt;
    # Valid as of JRuby 1.0
    
    # This is the 'magical Java require line'.
    require 'java'
    
    # With the 'require' above, we can now refer to things that are part of the
    # standard Java platform via their full paths.
    frame = javax.swing.JFrame.new(&amp;quot;Window&amp;quot;) # Creating a Java JFrame
    label = javax.swing.JLabel.new(&amp;quot;Hello&amp;quot;)
    
    # We can transparently call Java methods on Java objects, just as if they were defined in Ruby.
    frame.getContentPane.add(label)  # Invoking the Java method 'getContentPane'.
    frame.setDefaultCloseOperation(javax.swing.JFrame::EXIT_ON_CLOSE)
    frame.pack
    frame.setVisible(true)
&lt;/pre&gt;

&lt;/p&gt;&lt;p&gt;&lt;b&gt;Note:&lt;/b&gt; If you are testing the example above in the Swing IRB console &lt;b&gt;jirb_swing&lt;/b&gt;, change the default close operation to DISPOSE_ON_CLOSE, or HIDE_ON_CLOSE unless you want &lt;b&gt;jirb_swing&lt;/b&gt; to also close when you close the second window.

&lt;/p&gt;&lt;p&gt;Here's another example (showing results from testing these statements in the &lt;b&gt;jirb&lt;/b&gt; console). 

&lt;/p&gt;&lt;p&gt;Let's say you wanted to get a list of network interfaces. You can get Java API docs at &lt;tt&gt;&lt;a class='external' href=&quot;http://java.sun.com/j2se/1.5.0/docs/api/index.html/&quot;&gt;java.net.NetworkInterface&lt;/a&gt;&lt;/tt&gt;. 

&lt;/p&gt;&lt;p&gt;Here's how to access the methods from this Java Class from from JRuby:

&lt;/p&gt;&lt;pre&gt;  irb(main):013:0&amp;gt; ni = java.net.NetworkInterface.networkInterfaces
  =&amp;gt; #&amp;lt;#&amp;lt;Class:01x7e666f&amp;gt;:0x855a27 @java_object=java.net.NetworkInterface$1@821453&amp;gt;
&lt;/pre&gt;&lt;p&gt;&lt;b&gt;&lt;tt&gt;ni&lt;/tt&gt;&lt;/b&gt; is a Ruby variable holding a Java Enumeration of NetworkInterfaces. You can see the Class ancestry for &lt;tt&gt;ni&lt;/tt&gt; like this:

&lt;/p&gt;&lt;pre&gt;  irb(main):029:0&amp;gt; ni.class.ancestors
  =&amp;gt; [#&amp;lt;Class:01x7e666f&amp;gt;, Java::JavaUtil::Enumeration, Enumerable, Java::JavaLang::Object, 
  ConcreteJavaProxy, JavaProxy, JavaProxyMethods, Object, Java, Kernel]
&lt;/pre&gt;&lt;p&gt;
Enumeration elements can't be accessed using Array#[] syntax but they do appear as Arrays for many other purposes. You can find out both the Java and Ruby methods for an Enumeration of NetworkInterfaces like this:

&lt;/p&gt;&lt;pre&gt;  irb(main):032:0&amp;gt; java.net.NetworkInterface.networkInterfaces.methods
  =&amp;gt; [&amp;quot;__jsend!&amp;quot;, &amp;quot;has_more_elements&amp;quot;, &amp;quot;hasMoreElements&amp;quot;, &amp;quot;next_element&amp;quot;, &amp;quot;nextElement&amp;quot;,
  &amp;quot;each&amp;quot;, &amp;quot;reject&amp;quot;, &amp;quot;member?&amp;quot;, &amp;quot;grep&amp;quot;, &amp;quot;include?&amp;quot;, &amp;quot;min&amp;quot;, &amp;quot;sort&amp;quot;, &amp;quot;any?&amp;quot;, &amp;quot;partition&amp;quot;, 
  &amp;quot;each_with_index&amp;quot;, &amp;quot;collect&amp;quot;, &amp;quot;find_all&amp;quot;, &amp;quot;to_a&amp;quot;,  &amp;quot;inject&amp;quot;, &amp;quot;detect&amp;quot;, &amp;quot;map&amp;quot;, &amp;quot;zip&amp;quot;, 
  &amp;quot;sort_by&amp;quot;, &amp;quot;max&amp;quot;, &amp;quot;entries&amp;quot;, &amp;quot;all?&amp;quot;, &amp;quot;find&amp;quot;, &amp;quot;select&amp;quot;, &amp;quot;hashCode&amp;quot;, &amp;quot;notifyAll&amp;quot;, 
  &amp;quot;getClass&amp;quot;, &amp;quot;to_string&amp;quot;, &amp;quot;toString&amp;quot;, &amp;quot;get_class&amp;quot;, &amp;quot;notify_all&amp;quot;, &amp;quot;equals&amp;quot;, 
  &amp;quot;hash_code&amp;quot;, &amp;quot;wait&amp;quot;, &amp;quot;notify&amp;quot;, &amp;quot;__jcreate!&amp;quot;, &amp;quot;java_class&amp;quot;, &amp;quot;eql?&amp;quot;, &amp;quot;synchronized&amp;quot;, 
  &amp;quot;to_java_object&amp;quot;, &amp;quot;equal?&amp;quot;, &amp;quot;java_object&amp;quot;, &amp;quot;java_object=&amp;quot;, &amp;quot;to_s&amp;quot;, &amp;quot;==&amp;quot;, &amp;quot;hash&amp;quot;,
  &amp;quot;java_kind_of?&amp;quot;, &amp;quot;handle_different_imports&amp;quot;, &amp;quot;include_class&amp;quot;, &amp;quot;display&amp;quot;, 
  &amp;quot;object_id&amp;quot;, &amp;quot;frozen?&amp;quot;, &amp;quot;org&amp;quot;, &amp;quot;__id__&amp;quot;, &amp;quot;clone&amp;quot;, &amp;quot;__send__&amp;quot;, &amp;quot;id&amp;quot;, &amp;quot;__jtrap&amp;quot;, 
  &amp;quot;instance_eval&amp;quot;,  &amp;quot;singleton_methods&amp;quot;, &amp;quot;is_a?&amp;quot;, &amp;quot;extend&amp;quot;, 
  &amp;quot;instance_variable_set&amp;quot;, &amp;quot;freeze&amp;quot;, &amp;quot;remove_instance_variable&amp;quot;, &amp;quot;=~&amp;quot;,
  &amp;quot;private_methods&amp;quot;, &amp;quot;methods&amp;quot;, &amp;quot;instance_variable_get&amp;quot;, &amp;quot;nil?&amp;quot;, &amp;quot;send&amp;quot;, 
  &amp;quot;untaint&amp;quot;, &amp;quot;com&amp;quot;, &amp;quot;type&amp;quot;, &amp;quot;class&amp;quot;, &amp;quot;===&amp;quot;, &amp;quot;instance_of?&amp;quot;, 
  &amp;quot;protected_methods&amp;quot;, &amp;quot;tainted?&amp;quot;, &amp;quot;kind_of?&amp;quot;, &amp;quot;javax&amp;quot;, &amp;quot;inspect&amp;quot;, &amp;quot;java&amp;quot;, 
  &amp;quot;instance_exec&amp;quot;, &amp;quot;taint&amp;quot;, &amp;quot;dup&amp;quot;, &amp;quot;public_methods&amp;quot;, &amp;quot;instance_variable_defined?&amp;quot;, 
   &amp;quot;respond_to?&amp;quot;, &amp;quot;method&amp;quot;, &amp;quot;instance_variables&amp;quot;]
&lt;/pre&gt;&lt;p&gt;
Because JRuby supports the &lt;tt&gt;#each&lt;/tt&gt; method on Java Enumerations you can do this:

&lt;/p&gt;&lt;pre&gt;  irb(main):011:0&amp;gt; java.net.NetworkInterface.networkInterfaces.each {|i| puts i; puts }
  name:en1 (en1) index: 5 addresses:
  /63.138.152.170;
  /fe80:0:0:0:21b:63ff:febf:4a9d%5;
  
  name:en0 (en0) index: 4 addresses:
  /63.138.152.125;
  /fe80:0:0:0:21b:63ff:fe1e:b2da%4;
  
  name:lo0 (lo0) index: 1 addresses:
  /127.0.0.1;
  /fe80:0:0:0:0:0:0:1%1;
  /0:0:0:0:0:0:0:1%0;
&lt;/pre&gt;&lt;h2&gt;&lt;a name='Accessing_and_Importing_Java_Classes'&gt;&lt;/a&gt; Accessing and Importing Java Classes &lt;/h2&gt;
&lt;h3&gt;&lt;a name='Require_a_jar_file_to_make_resources_in_the_jar_discoverable_within_JRuby'&gt;&lt;/a&gt; Require a jar file to make resources in the jar discoverable within JRuby &lt;/h3&gt;
&lt;p&gt;To use resources within a jar file from JRuby, the jar file must either be on the classpath or be made available with the &lt;tt&gt;require&lt;/tt&gt; method:

&lt;/p&gt;&lt;pre&gt;  require 'path/to/mycode.jar'
&lt;/pre&gt;&lt;p&gt;
This &lt;tt&gt;require&lt;/tt&gt; makes the resources in &lt;tt&gt;mycode.jar&lt;/tt&gt; discoverable by commands like &lt;tt&gt;import&lt;/tt&gt; and &lt;tt&gt;include_package&lt;/tt&gt;.

&lt;/p&gt;&lt;p&gt;Note that loading jar-files via &lt;tt&gt;require&lt;/tt&gt; searches along the RUBYLIB path, like normal ruby files.

&lt;/p&gt;&lt;h3&gt;&lt;a name='Naming_a_Java_Class'&gt;&lt;/a&gt; Naming a Java Class &lt;/h3&gt;
&lt;p&gt;You can name a Java class in JRuby in at least three different ways. The idea is to map Java names like &lt;tt&gt;org.foo.department.Widget&lt;/tt&gt; to Ruby nested modules. This works as follows:

&lt;/p&gt;&lt;pre&gt;   Java: org.foo.department.Widget
   Ruby: Java::OrgFooDepartment::Widget
&lt;/pre&gt;&lt;p&gt;
That is:

&lt;/p&gt;&lt;ul&gt;&lt;li&gt; Java packages reside in the &lt;tt&gt;Java&lt;/tt&gt; module.
&lt;/li&gt;&lt;li&gt; The package path is transformed by removing the dots and converting to &lt;i&gt;CamelCase&lt;/i&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;
This also means that, just as in Java, packages are not nested.

&lt;/p&gt;&lt;ul&gt;&lt;li&gt; For the top-level Java packages &lt;tt&gt;java&lt;/tt&gt;, &lt;tt&gt;javax&lt;/tt&gt;, &lt;tt&gt;org&lt;/tt&gt;, and &lt;tt&gt;com&lt;/tt&gt; you can type in a fully qualified class name basically as in Java, for example, &lt;tt&gt;java.lang.System&lt;/tt&gt;.
&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;
You can get the same effect for your own top-level packages, as follows. Let's assume that your packages are called &lt;tt&gt;edu.school.department.Class&lt;/tt&gt;. Then, you define

&lt;/p&gt;&lt;pre&gt;   def edu
      Java::Edu
   end
&lt;/pre&gt;&lt;p&gt;
And you can use the usual Java package names.

&lt;/p&gt;&lt;p&gt;As of JRuby-1.1.5, the &lt;tt&gt;import&lt;/tt&gt; statement only works with either Java-style names or strings, but not with the &lt;tt&gt;Java::PackagePath::Class&lt;/tt&gt; variant.

&lt;/p&gt;&lt;h3&gt;&lt;a name='Import_a_Java_Class_to_Use_It_Without_The_Full_Path_Name'&gt;&lt;/a&gt; Import a Java Class to Use It Without The Full Path Name &lt;/h3&gt;
&lt;p&gt;
You can always access any Java class that has been loaded or is in the classpath by specifying its full name. With the &lt;tt&gt;java_import&lt;/tt&gt; statement or &lt;tt&gt;import&lt;/tt&gt; statement, you can make the Java class available only by its name, just as in Java.

&lt;/p&gt;&lt;p&gt;&lt;b&gt;Example&lt;/b&gt;: import and use the &lt;tt&gt;java.lang.System&lt;/tt&gt; class.

&lt;/p&gt;&lt;pre&gt;  require 'java'
  java_import java.lang.System
  version = System.getProperties[&amp;quot;java.runtime.version&amp;quot;]
&lt;/pre&gt;&lt;p&gt;&lt;b&gt;Note:&lt;/b&gt; As noted in &lt;a class='external' href=&quot;http://jira.codehaus.org/browse/JRUBY-3171&quot;&gt;this bug report&lt;/a&gt;, &lt;tt&gt;java_import&lt;/tt&gt; is the preferred, and safer, way to import Java classes.

&lt;/p&gt;&lt;h3&gt;&lt;a name='Use_include_package_within_a_Ruby_Module_to_import_a_Java_Package'&gt;&lt;/a&gt; Use include_package within a Ruby Module to import a Java Package &lt;/h3&gt;
&lt;p&gt;
Use &lt;tt&gt;include_package &amp;quot;package_name&amp;quot;&lt;/tt&gt; in a Ruby Module to support namespaced access to the Java classes in the package. It is also legal to use &lt;tt&gt;import &amp;quot;package_name&amp;quot;&lt;/tt&gt;.

&lt;/p&gt;&lt;p&gt;&lt;b&gt;Example&lt;/b&gt;: create a Ruby Module called &lt;tt&gt;JavaLang&lt;/tt&gt; that includes the classes in the Java package &lt;tt&gt;java.lang&lt;/tt&gt;.

&lt;/p&gt;&lt;pre&gt;  module JavaLang
    include_package &amp;quot;java.lang&amp;quot;
    # alternately, use the #import method
    import &amp;quot;java.lang&amp;quot;
  end
&lt;/pre&gt;&lt;p&gt;
Prefix the Class name with &lt;tt&gt;JavaLang::&lt;/tt&gt; to access the included Classes:

&lt;/p&gt;&lt;pre&gt;  version = JavaLang::System.getProperties[&amp;quot;java.runtime.version&amp;quot;]
  =&amp;gt; &amp;quot;1.5.0_13-b05-237&amp;quot;
&lt;/pre&gt;&lt;pre&gt;  processors = JavaLang::Runtime.getRuntime.availableProcessors
  =&amp;gt; 2
&lt;/pre&gt;&lt;p&gt;
The Java classes in the package will become available in this class/module, unless a constant with the same name as a Java class is already defined.

&lt;/p&gt;&lt;p&gt;The use of the Module name to scope access to the imported Java class is also helpful in cases where the Java class has the same name as an existing Ruby class. 

&lt;/p&gt;&lt;p&gt;For example if you need to create an instance of a &lt;tt&gt;java.io.File&lt;/tt&gt; object, this code will work:

&lt;/p&gt;&lt;pre&gt;  import java.io.File
  newfile = File.new(&amp;quot;file.txt&amp;quot;)
  =&amp;gt; #&amp;lt;Java::JavaIo::File:0xdc6f00 @java_object=file.txt&amp;gt;
&lt;/pre&gt;&lt;p&gt;
However you've now redefined the Ruby constant File and can no longer access the Ruby File class. Executing this:

&lt;/p&gt;&lt;pre&gt;  File.open('README', 'r') {|f| puts f.readline }
&lt;/pre&gt;&lt;p&gt;
Will produce this error:

&lt;/p&gt;&lt;pre&gt;  NoMethodError: private method `open' called for Java::JavaIo::File:Class
&lt;/pre&gt;&lt;p&gt;
If instead you create a module called &lt;tt&gt;JavaIO&lt;/tt&gt; and include the package in the module definition:

&lt;/p&gt;&lt;pre&gt;  module JavaIO     
    include_package &amp;quot;java.io&amp;quot;
  end
&lt;/pre&gt;&lt;p&gt;
You can now create a new instance of the Java class File without shadowing the Ruby version of the File class:

&lt;/p&gt;&lt;pre&gt;  newfile = JavaIO::File.new(&amp;quot;file.txt&amp;quot;)
  =&amp;gt; #&amp;lt;Java::JavaIo::File:0x15619c @java_object=file.txt&amp;gt;
&lt;/pre&gt;&lt;p&gt;
The Ruby File class is still accessible:

&lt;/p&gt;&lt;pre&gt;  File.open('README', 'r') {|f| puts f.readline }
  JRuby -  A Java implementation of the Ruby language
  =&amp;gt; nil
&lt;/pre&gt;&lt;h3&gt;&lt;a name='Accessing_Java_Enumerations'&gt;&lt;/a&gt; Accessing Java Enumerations &lt;/h3&gt;
&lt;p&gt;Java &lt;tt&gt;enum&lt;/tt&gt;s are accessible from Ruby code as constants:

&lt;/p&gt;&lt;pre&gt;  lock.try_lock(5000, java.util.concurrent.TimeUnit::MILLISECONDS)
&lt;/pre&gt;&lt;p&gt;
or 

&lt;/p&gt;&lt;pre&gt;  java_import java.util.concurrent.TimeUnit
  lock.try_lock(5000, TimeUnit::MILLISECONDS)
&lt;/pre&gt;&lt;h3&gt;&lt;a name='Gotchas'&gt;&lt;/a&gt; Gotchas &lt;/h3&gt;
&lt;p&gt;
JRuby automatically binds the following names in the context of a class to the top-level Java packages: com, org, java, javax. This means that you can reference these packages without having to explicitly require or import them. This takes effect for all Ruby classes in an application where a require 'java' appears. This binding takes place in precedence to the classes &amp;quot;method_missing&amp;quot; handling.

&lt;/p&gt;&lt;p&gt;If you do not want this behaviour for a specific class, you can undefine it for that class. Here's an example that will execute identically under Ruby and JRuby:

&lt;/p&gt;&lt;p&gt;&lt;pre&gt;
# Note: Comment out for Ruby test. Uncomment for JRuby test.
require 'java'

class MethodMissing
  # JRuby: Undefine the standard &amp;quot;automatic&amp;quot; bindings to Java, to avoid any automatic binding.
  undef org, com, java, javax
  
  def method_missing(m, *args)
    puts &amp;quot;method_missing: #{m}.&amp;quot;
    &amp;quot;This is what I return from method missing.&amp;quot;
  end
end

mm = MethodMissing.new
result = mm.org
puts &amp;quot;Result: #{result} Type: #{result.class.name}&amp;quot;
&lt;/pre&gt;

&lt;/p&gt;&lt;h2&gt;&lt;a name='Calling_a_Java_Method'&gt;&lt;/a&gt; Calling a Java Method &lt;/h2&gt;
&lt;h3&gt;&lt;a name='Alternative_Names_and_Beans_Convention'&gt;&lt;/a&gt; Alternative Names and Beans Convention &lt;/h3&gt;
&lt;p&gt;
In Ruby, one usually prefers &lt;tt&gt;method_names_like_this&lt;/tt&gt;, while Java traditionally uses &lt;tt&gt;methodNamesLikeThis&lt;/tt&gt;. If you want, you can use Ruby-style method names instead of the Java ones.

&lt;/p&gt;&lt;p&gt;For example, these two calls are equivalent

&lt;/p&gt;&lt;pre&gt;  java.lang.System.currentTimeMillis
  java.lang.System.current_time_millis
&lt;/pre&gt;&lt;p&gt;
JRuby also translates methods following the 'beans-convention':

&lt;/p&gt;&lt;pre&gt;  x.getSomething            becomes   x.something
  x.setSomething(newValue)  becomes   x.something = new_value
  x.isSomething             becomes   x.something?
&lt;/pre&gt;&lt;p&gt;
You don't have to use these alternatives, but they can make the interaction with Java code feel more Ruby-like.

&lt;/p&gt;&lt;h3&gt;&lt;a name='Beware_of_Java_generics'&gt;&lt;/a&gt; Beware of Java generics &lt;/h3&gt;
&lt;p&gt;
If a Java class is defined with Java generics, the types are erased during compilation for backwards compatibility. As a result. JRuby will have problems with automatic type conversion. For example, if you have a &lt;tt&gt;Map&amp;lt;String,String&amp;gt;&lt;/tt&gt;, it will be seen as a simple &lt;tt&gt;Map&lt;/tt&gt;, and JRuby will not be able to determine the correct types using reflection.

&lt;/p&gt;&lt;h3&gt;&lt;a name='Additional_Methods'&gt;&lt;/a&gt; Additional Methods &lt;/h3&gt;
&lt;p&gt;
JRuby defines a number of additional methods for Java objects.

&lt;/p&gt;&lt;ul&gt;&lt;li&gt; &lt;tt&gt;java_class&lt;/tt&gt; returns the Java class of an object.
&lt;/li&gt;&lt;li&gt; &lt;tt&gt;java_kind_of?&lt;/tt&gt; works like the &lt;tt&gt;instanceof&lt;/tt&gt; operator.
&lt;/li&gt;&lt;li&gt; &lt;tt&gt;java_object&lt;/tt&gt; returns the underlying Java object. This is useful for reflection.
&lt;/li&gt;&lt;li&gt; &lt;tt&gt;java_send&lt;/tt&gt; overrides JRuby's dispatch rules and forces the execution of a named Java method on a Java object. This is useful for Java methods, such as &lt;tt&gt;initialize&lt;/tt&gt;, with names that conflict with built-in Ruby methods. More below. &lt;i&gt;Added in JRuby 1.4&lt;/i&gt;&lt;/li&gt;&lt;li&gt; &lt;tt&gt;java_method&lt;/tt&gt; retrieves a bound or unbound handle for a Java method to avoid the reflection inherent in &lt;tt&gt;java_send&lt;/tt&gt;. More below. &lt;i&gt;Added in JRuby 1.4&lt;/i&gt;&lt;/li&gt;&lt;/ul&gt;&lt;h3&gt;&lt;a name='Calling_masked_or_unreachable_Java_methods_with_java_send'&gt;&lt;/a&gt; Calling masked or unreachable Java methods with &lt;tt&gt;java_send&lt;/tt&gt; &lt;/h3&gt;
&lt;p&gt;Sometimes you need to call &lt;tt&gt;initialize&lt;/tt&gt; AFTER the &lt;tt&gt;.new()&lt;/tt&gt; call, for example the &lt;tt&gt;RTPManager&lt;/tt&gt; class in JMF. Unfortunately, this method is masked by Ruby's &lt;tt&gt;initialize&lt;/tt&gt; constructor method.  As of JRuby 1.4, the &lt;tt&gt;java_send&lt;/tt&gt; method can be used to call this, and any other, masked method:

&lt;/p&gt;&lt;pre&gt;  @mgr = javax.media.rtp.RTPManager.newInstance
  localhost = java.net.InetAddress.getByName(&amp;quot;127.0.0.1&amp;quot;)
  localaddr = javax.media.rtp.SessionAddress.new(localhost, 21000, localhost, 21001)
  @mgr.java_send :initialize, [javax.media.rtp.SessionAddress], localaddr
&lt;/pre&gt;&lt;p&gt;
In previous versions of JRuby, the same thing can be accomplised with reflection:

&lt;/p&gt;&lt;pre&gt;  @mgr = javax.media.rtp.RTPManager.newInstance
  localhost = java.net.InetAddress.getByName(&amp;quot;127.0.0.1&amp;quot;)
  localaddr = javax.media.rtp.SessionAddress.new(localhost, 21000, localhost, 21001)
  method = @mgr.java_class.declared_method(:initialize, javax.media.rtp.SessionAddress )
  method.invoke @mgr.java_object, localaddr.java_object
&lt;/pre&gt;&lt;p&gt;
Here is another example of calling the &lt;tt&gt;ArrayList.add&lt;/tt&gt; method with &lt;tt&gt;java_send&lt;/tt&gt;:

&lt;/p&gt;&lt;pre&gt; 
 import java.util.ArrayList
 list = ArrayList.new
 list.java_send :add, [Java::int, java.lang.Object], 0, 'foo'
 puts list.java_send :toString # =&amp;gt; &amp;quot;[foo]&amp;quot;
&lt;/pre&gt;&lt;p&gt;
Note the second argument, which is an array of types indicating the exact method signature desired. This is useful for disambiguating methods that are overloaded on similar types such as &lt;tt&gt;int&lt;/tt&gt; and &lt;tt&gt;long&lt;/tt&gt;.

&lt;/p&gt;&lt;h3&gt;&lt;a name='Bound_and_Unbound_Java_methods_with_java_method'&gt;&lt;/a&gt; Bound and Unbound Java methods with &lt;tt&gt;java_method&lt;/tt&gt; &lt;/h3&gt;
&lt;p&gt;&lt;tt&gt;java_send&lt;/tt&gt; relies on reflection and may lead to poor performance in some cases. Each time it is called, the desired method must be relocated. With the &lt;tt&gt;java_method&lt;/tt&gt; method you can get a reference to any overloaded Java method as a Ruby Method object:

&lt;/p&gt;&lt;pre&gt; 
 # get a bound Method based on the add(int, Object) method from ArrayList
 add = list.java_method :add, [Java::int, java.lang.Object]
 add.call(0, 'foo')
 
&lt;/pre&gt;&lt;p&gt;
Similarly, an Unbound method object can be retrieved:

&lt;/p&gt;&lt;pre&gt; # get an UnboundMethod from the ArrayList class:
 toString = ArrayList.java_method :toString
 toString.bind(list).call # =&amp;gt; [foo, foo]
&lt;/pre&gt;&lt;h3&gt;&lt;a name='Conversion_of_Types'&gt;&lt;/a&gt; Conversion of Types &lt;/h3&gt;
&lt;h4&gt;&lt;a name='Ruby_to_Java'&gt;&lt;/a&gt; Ruby to Java &lt;/h4&gt;
&lt;p&gt;&lt;i&gt;See the JRuby rspec source code dir&lt;/i&gt; &lt;tt&gt;spec/java_integration&lt;/tt&gt; &lt;i&gt;for many more examples.&lt;/i&gt;

&lt;/p&gt;&lt;p&gt;When calling Java from JRuby, primitive Ruby types are converted to default boxed Java types:

&lt;/p&gt;&lt;div style=&quot;overflow-x: auto;&quot;&gt;&lt;div style=&quot;margin: 0px 2px 0px 2px;&quot;&gt;
&lt;table border=&quot;1&quot; style=&quot;text-align:left;&quot; cellspacing=&quot;2&quot; cellpadding=&quot;5&quot;&gt;&lt;tr style=&quot;background:silver&quot;&gt;&lt;td&gt;&lt;b&gt;Ruby Type&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;Java Type&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr &gt;&lt;td&gt;  &amp;quot;foo&amp;quot; &lt;/td&gt;&lt;td&gt; &lt;tt&gt;java.lang.String&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt; 1 &lt;/td&gt;&lt;td&gt; &lt;tt&gt;java.lang.Long&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt; 1.0 &lt;/td&gt;&lt;td&gt; &lt;tt&gt;java.lang.Double&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt; true, false &lt;/td&gt;&lt;td&gt; &lt;tt&gt;java.lang.Boolean&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt; 1 &amp;lt;&amp;lt; 128 &lt;/td&gt;&lt;td&gt; &lt;tt&gt;java.math.BigInteger&lt;/tt&gt; 
&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;
&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;
However, this does not mean that you cannot call methods expecting a primitive type. You can also pass an integer to a method expecting a double value. JRuby usually tries quite hard to find a method that can understand your parameters.

&lt;/p&gt;&lt;p&gt;If JRuby cannot find a matching method, it tries to pass the actual JRuby objects instead (that is, the Java objects from the JRuby implementation). A consequence of this is that if this fails you will see an error message stating that JRuby hasn't found a method taking an object of class &lt;tt&gt;org.jruby.RubyObject&lt;/tt&gt; instead of the actual type.

&lt;/p&gt;&lt;p&gt;If JRuby is not finding the exact method you want to call, perhaps because of extreme ambiguity like &lt;tt&gt;foo(int)&lt;/tt&gt; vs. &lt;tt&gt;foo(long)&lt;/tt&gt;, the &lt;tt&gt;java_send&lt;/tt&gt; method can be used to disambiguate. See below.

&lt;/p&gt;&lt;h4&gt;&lt;a name='Java_to_Ruby'&gt;&lt;/a&gt; Java to Ruby &lt;/h4&gt;
&lt;p&gt;When primitive Java types are passed to JRuby they are converted to the following Ruby types:

&lt;/p&gt;&lt;div style=&quot;overflow-x: auto;&quot;&gt;&lt;div style=&quot;margin: 0px 2px 0px 2px;&quot;&gt;
&lt;table border=&quot;1&quot; style=&quot;text-align:left;&quot; cellspacing=&quot;2&quot; cellpadding=&quot;5&quot;&gt;&lt;tr style=&quot;background:silver&quot;&gt;&lt;td&gt;&lt;b&gt;Java Type&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;Ruby Type&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr &gt;&lt;td&gt; &lt;tt&gt;public String&lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt;String&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt; &lt;tt&gt;public byte&lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt;Fixnum&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt; &lt;tt&gt;public short&lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt;Fixnum&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt; &lt;tt&gt;public char&lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt;Fixnum&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt; &lt;tt&gt;public int&lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt;Fixnum&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt; &lt;tt&gt;public long&lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt;Fixnum&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt; &lt;tt&gt;public float&lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt;Float&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt; &lt;tt&gt;public double&lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt;Float&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;
&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;
The Java Booleans true and false are coerced to the Ruby singleton classes TrueClass and FalseClass which are represented in Ruby with the instances true and false.

&lt;/p&gt;&lt;p&gt;The null Java object is coerced to the Ruby class NilClass which is represented in Ruby as the instance nil.

&lt;/p&gt;&lt;h4&gt;&lt;a name='Java_Primitive_Classes'&gt;&lt;/a&gt; Java Primitive Classes &lt;/h4&gt;
&lt;p&gt;
Java primitive classes can be found in the Java module. For example, &lt;code&gt;Java::byte&lt;/code&gt; represents the primitive type byte in java. You can get its class as follows:

&lt;/p&gt;&lt;div style=&quot;overflow-x: auto;&quot;&gt;&lt;div style=&quot;margin: 0px 2px 0px 2px;&quot;&gt;
&lt;table border=&quot;1&quot;&gt;&lt;tr style=&quot;background:silver&quot;&gt;&lt;td&gt;&lt;b&gt;Ruby Code&lt;/b&gt; &lt;/td&gt;&lt;td&gt;&lt;b&gt;Java Class&lt;/b&gt; 
&lt;/td&gt;&lt;/tr&gt;
&lt;tr &gt;&lt;td&gt; &lt;tt&gt;Java::JavaClass.for_name(&amp;quot;byte&amp;quot;) &lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt;Java::byte.java_class&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr &gt;&lt;td&gt; &lt;tt&gt;Java::JavaClass.for_name(&amp;quot;boolean&amp;quot;) &lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt; Java::boolean.java_class&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr &gt;&lt;td&gt; &lt;tt&gt;Java::JavaClass.for_name(&amp;quot;byte&amp;quot;) &lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt; Java::byte.java_class&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr &gt;&lt;td&gt; &lt;tt&gt;Java::JavaClass.for_name(&amp;quot;short&amp;quot;) &lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt; Java::short.java_class&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr &gt;&lt;td&gt; &lt;tt&gt;Java::JavaClass.for_name(&amp;quot;char&amp;quot;) &lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt; Java::char.java_class&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr &gt;&lt;td&gt; &lt;tt&gt;Java::JavaClass.for_name(&amp;quot;int&amp;quot;) &lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt; Java::int.java_class&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr &gt;&lt;td&gt; &lt;tt&gt;Java::JavaClass.for_name(&amp;quot;long&amp;quot;) &lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt; Java::long.java_class&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr &gt;&lt;td&gt; &lt;tt&gt;Java::JavaClass.for_name(&amp;quot;float&amp;quot;) &lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt; Java::float.java_class&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr &gt;&lt;td&gt; &lt;tt&gt;Java::JavaClass.for_name(&amp;quot;double&amp;quot;) &lt;/tt&gt; &lt;/td&gt;&lt;td&gt; &lt;tt&gt; Java::double.java_class&lt;/tt&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;
&lt;/div&gt;&lt;/div&gt;
&lt;h2&gt;&lt;a name='Arrays'&gt;&lt;/a&gt; Arrays &lt;/h2&gt;
&lt;p&gt;There are two ways of constructing Java arrays. One is to use the &lt;code&gt;to_java&lt;/code&gt; method of the class Array. The other is to use the &lt;tt&gt;[]&lt;/tt&gt; method for the primitive Java types.

&lt;/p&gt;&lt;h4&gt;&lt;a name='Converting_a_Ruby_Array_to_a_Java_Array'&gt;&lt;/a&gt; Converting a Ruby Array to a Java Array &lt;/h4&gt;
&lt;p&gt;The &lt;tt&gt;to_java&lt;/tt&gt; method constructs a Java array from a Ruby array:

&lt;/p&gt;&lt;pre&gt;  [1,2,3].to_java
  =&amp;gt; [Ljava.lang.Object;@1a32ea4
&lt;/pre&gt;&lt;p&gt;
By default, &lt;tt&gt;to_java&lt;/tt&gt; constructs &lt;tt&gt;Object&lt;/tt&gt; arrays. You can specify the parameter with an additional argument which can either be a symbol or a primitive class like &lt;tt&gt;Java::double&lt;/tt&gt;

&lt;/p&gt;&lt;pre&gt;  [&amp;quot;a&amp;quot;,&amp;quot;b&amp;quot;,&amp;quot;c&amp;quot;].to_java(:string)
  =&amp;gt; [Ljava.lang.String;@170984c
&lt;/pre&gt;&lt;pre&gt;  [1, 2, 3.5].to_java Java::double
  =&amp;gt; [D@9bc984
&lt;/pre&gt;&lt;h4&gt;&lt;a name='Constructing_Empty_Java_Arrays'&gt;&lt;/a&gt; Constructing Empty Java Arrays &lt;/h4&gt;
&lt;p&gt;Sometimes a Java library will need a fixed-length array, say for example a byte buffer for a stream to read into. For this, you can use the &lt;tt&gt;[]&lt;/tt&gt; method of the primitive types in the Java module:

&lt;/p&gt;&lt;pre&gt;  bytes = Java::byte[1024].new # Equivalent to Java's bytes = new byte[1024];
&lt;/pre&gt;&lt;h3&gt;&lt;a name='Ruby_String_to_Java_Bytes_and_back_again'&gt;&lt;/a&gt; Ruby String to Java Bytes and back again &lt;/h3&gt;
&lt;pre&gt;  bytes = 'a string'.to_java_bytes
  =&amp;gt; #&amp;lt;#&amp;lt;Class:01x9fcffd&amp;gt;:0x40e825 @java_object=[B@3d476c&amp;gt;
&lt;/pre&gt;&lt;pre&gt;  string = String.from_java_bytes bytes
  =&amp;gt; &amp;quot;a string&amp;quot;
&lt;/pre&gt;&lt;h3&gt;&lt;a name='Convert_a_Java_InputStream_to_a_ruby_IO_object'&gt;&lt;/a&gt; Convert a Java InputStream to a ruby IO object &lt;/h3&gt;
&lt;pre&gt;  io = Java.java_to_ruby(org.jruby.RubyIO.new(JRuby.runtime, input_stream).java_object)
&lt;/pre&gt;&lt;p&gt;&lt;a class='external' href=&quot;http://logs.jruby.org/jruby/2009-06-23.html#T21-34-32&quot;&gt;from ribrdb on irc&lt;/a&gt;&lt;/p&gt;&lt;pre&gt; 
&lt;/pre&gt;&lt;h2&gt;&lt;a name='Referencing_a_java.lang.Class_object'&gt;&lt;/a&gt; Referencing a &lt;tt&gt;java.lang.Class&lt;/tt&gt; object &lt;/h2&gt;
&lt;p&gt;If you call a Java class from JRuby and need to pass a Java class as an argument, if you use this form:

&lt;/p&gt;&lt;pre&gt;  DoSomethingWithJavaClass(MyJavaClass.class)
&lt;/pre&gt;&lt;p&gt;
you'll get this error:

&lt;/p&gt;&lt;pre&gt;  TypeError: expected [java.lang.Class]; 
  got: [org.jruby.RubyClass]; error: argument type mismatch
&lt;/pre&gt;&lt;p&gt;
Instead use the method &lt;tt&gt;java_class&lt;/tt&gt;.

&lt;/p&gt;&lt;pre&gt;  DoSomethingWithJavaClass(MyJavaClass.java_class)
&lt;/pre&gt;&lt;h2&gt;&lt;a name='Integrating_JRuby_and_Java_Classes_and_Interfaces'&gt;&lt;/a&gt; Integrating JRuby and Java Classes and Interfaces &lt;/h2&gt;
&lt;h3&gt;&lt;a name='Classes'&gt;&lt;/a&gt; Classes &lt;/h3&gt;
&lt;h4&gt;&lt;a name='Reopening_Java_Classes'&gt;&lt;/a&gt; Reopening Java Classes &lt;/h4&gt;
&lt;p&gt;In Ruby, classes are always open, which means that you can later add methods to existing classes. This also works with Java classes.

&lt;/p&gt;&lt;p&gt;This comes in handy when adding syntactic sugar like overloaded operators to Java classes, or other methods to make them behave more Ruby-like.

&lt;/p&gt;&lt;p&gt;Note that these additions will only be visible on the JRuby side. 

&lt;/p&gt;&lt;h4&gt;&lt;a name='Subclassing_a_Java_class'&gt;&lt;/a&gt; Subclassing a Java class &lt;/h4&gt;
&lt;p&gt;You can subclass (i.e. extend) a Java class and then use the JRuby class whenever Java expects the superclass.

&lt;/p&gt;&lt;h4&gt;&lt;a name='Gotchas'&gt;&lt;/a&gt; Gotchas &lt;/h4&gt;
&lt;p&gt;If you have a class name ambiguity between Java and Ruby, the class name will reference the Ruby construct within the Ruby code. For instance, if you import &lt;tt&gt;java.lang.Thread&lt;/tt&gt; and then write &lt;tt&gt;JThread &amp;lt; Thread&lt;/tt&gt;, &lt;tt&gt;JThread&lt;/tt&gt; will in fact inherit the Ruby &lt;tt&gt;Thread&lt;/tt&gt; object, not the Java &lt;tt&gt;Thread&lt;/tt&gt;. The solution is to use the full Java Class name, such as:
&lt;/p&gt;&lt;pre&gt; JThread &amp;lt; java.lang.Thread
&lt;/pre&gt;&lt;h3&gt;&lt;a name='Interfaces'&gt;&lt;/a&gt; Interfaces &lt;/h3&gt;
&lt;p&gt;Java interfaces are mapped to modules in JRuby. This means that you can also reopen the corresponding module and add further methods on the JRuby side.

&lt;/p&gt;&lt;h4&gt;&lt;a name='Implementing_Java_Interfaces_in_JRuby'&gt;&lt;/a&gt; Implementing Java Interfaces in JRuby &lt;/h4&gt;
&lt;p&gt;JRuby classes can now implement more than one Java interface. Since Java interfaces are mapped to modules in JRuby, you implement them not by subclassing, but by mixing them in.

&lt;/p&gt;&lt;pre&gt;  class SomeJRubyObject
    include java.lang.Runnable
    include java.lang.Comparable
  end
&lt;/pre&gt;&lt;h4&gt;&lt;a name='Closure_conversion'&gt;&lt;/a&gt; Closure conversion &lt;/h4&gt;
&lt;p&gt;JRuby sports a feature called &lt;i&gt;closure conversion&lt;/i&gt;, where a Ruby block or closure is converted to an appropriate Java interface. For example:

&lt;/p&gt;&lt;pre&gt;  button = javax.swing.JButton.new &amp;quot;Press me!&amp;quot;
  button.add_action_listener {|event| event.source.text = &amp;quot;You did it!&amp;quot;}
&lt;/pre&gt;&lt;p&gt;
In this example, the &lt;tt&gt;JButton&lt;/tt&gt;'s &lt;tt&gt;addActionListener&lt;/tt&gt; method takes one parameter, a &lt;tt&gt;java.awt.event.ActionListener&lt;/tt&gt;. The block is converted to a &lt;tt&gt;Proc&lt;/tt&gt; object, which is then decorated with a java interface proxy that invokes the block for any method called on the interface.

&lt;/p&gt;&lt;p&gt;This not only works for event listeners or &lt;tt&gt;Runnable&lt;/tt&gt;, but basically for any interface. When calling a method that expects an interface, JRuby checks if a block is passed and automatically converts the block to an object implementing the interface.

&lt;/p&gt;&lt;pre&gt; 
&lt;/pre&gt;&lt;h3&gt;&lt;a name='Java_classes_can_t_inherit_from_a_JRuby_class'&gt;&lt;/a&gt; Java classes can't inherit from a JRuby class &lt;/h3&gt;
&lt;p&gt;Hopefully this feature will be added in the planned re-write of the Java integration layer in a future release of JRuby.

&lt;/p&gt;&lt;h2&gt;&lt;a name='Exception_Handling'&gt;&lt;/a&gt; Exception Handling &lt;/h2&gt;
&lt;p&gt;Native Java exceptions can be caught in Ruby code as expected:

&lt;/p&gt;&lt;pre&gt; begin
   java.lang.Integer.parse_int(&amp;quot;asdf&amp;quot;)
 rescue java.lang.NumberFormatException =&amp;gt; e
   puts &amp;quot;Failed to parse integer: #{e.message}&amp;quot;
 end
&lt;/pre&gt;&lt;p&gt;
Furthermore, Ruby code can throw Java exceptions:

&lt;/p&gt;&lt;pre&gt; begin
   raise java.lang.IllegalArgumentException.new(&amp;quot;Bad param&amp;quot;)
 rescue java.lang.IllegalArgumentException =&amp;gt; e
   puts &amp;quot;Illegal argument: #{e}&amp;quot;
 end
&lt;/pre&gt;&lt;p&gt;
This is useful if you happen to be implementing a Java interface in Ruby that requires a particular exception to be thrown on error.

&lt;/p&gt;&lt;p&gt;Note that this can also be written:

&lt;/p&gt;&lt;pre&gt; begin
   raise Java::JavaLang::IllegalArgumentException.new(&amp;quot;Bad param&amp;quot;)
 rescue Java::JavaLang::IllegalArgumentException =&amp;gt; e
   puts &amp;quot;Illegal argument: #{e}&amp;quot;
 end
&lt;/pre&gt;&lt;h2&gt;&lt;a name='Synchronization_in_JRuby'&gt;&lt;/a&gt; Synchronization in JRuby &lt;/h2&gt;
&lt;p&gt;When interacting with Java APIs from JRuby, it is occasionally necessary to synchronize on an object for thread safety. In JRuby, a &lt;tt&gt;synchronize&lt;/tt&gt; method is provided on every wrapped Java object to support this functionality. For example, the following Java code:

&lt;/p&gt;&lt;pre&gt; 
 synchronized(obj) {
     obj.wait(1000); 
 }
 
&lt;/pre&gt;&lt;p&gt;
is implement like this in Ruby:

&lt;/p&gt;&lt;pre&gt; 
 obj.synchronized do
   obj.wait 1000
 end
 
&lt;/pre&gt;&lt;p&gt;The expression evaluates to the result of the block, e.g.,

&lt;/p&gt;&lt;pre&gt; 
 obj.synchronized { 99 }  # =&amp;gt; 99
 
&lt;/pre&gt;&lt;h2&gt;&lt;a name='Material_from_Before_JRuby_1.0'&gt;&lt;/a&gt; Material from Before JRuby 1.0 &lt;/h2&gt;
&lt;p&gt;One powerful feature of JRuby is its ability to invoke the classes of the Java Platform. The following example uses JRuby 0.9.2 to create a Java &lt;tt&gt;JFrame&lt;/tt&gt; with a &lt;tt&gt;JLabel&lt;/tt&gt;. 

&lt;/p&gt;&lt;p&gt;&lt;b&gt;Note:&lt;/b&gt; Several package paths are magic: &lt;tt&gt;java&lt;/tt&gt;, &lt;tt&gt;javax&lt;/tt&gt;, &lt;tt&gt;org&lt;/tt&gt;, &lt;tt&gt;com&lt;/tt&gt;.  Many package paths will need to be prefixed with &lt;tt&gt;Java&lt;/tt&gt;:

&lt;/p&gt;&lt;p&gt;&lt;pre name=&quot;code&quot; class=&quot;ruby&quot;&gt;
require 'java'

JFrame = javax.swing.JFrame
JLabel = javax.swing.JLabel

frame = JFrame.new()
frame.getContentPane().add(JLabel.new(&amp;quot;This is an example.&amp;quot;))
frame.pack()
frame.setVisible(true)

MyClass = Java::my.package.MyClass
myClass = MyClass.new()
myClass.doit()
&lt;/pre&gt;

&lt;/p&gt;&lt;p&gt;&lt;b&gt;Note:&lt;/b&gt; Older versions of JRuby require you to use the following code as the import preamble:

&lt;/p&gt;&lt;p&gt;&lt;pre name=&quot;code&quot; class=&quot;ruby&quot;&gt;
require 'java'

include_class &amp;quot;javax.swing.JFrame&amp;quot;
include_class &amp;quot;javax.swing.JLabel&amp;quot;
&lt;/pre&gt;

&lt;/p&gt;&lt;p&gt;JRuby also allows you to call Java code by using the more Ruby-like &lt;tt&gt;underscore_method_naming&lt;/tt&gt; and to refer to JavaBean properties as attributes. The translation rule is that the Java method name is split by capital letters, lowercased, and prepended with &lt;tt&gt;_&lt;/tt&gt;.
&lt;pre name=&quot;code&quot; class=&quot;ruby&quot;&gt;
frame.content_pane.add(label)
frame.visible = true
&lt;/pre&gt;

&lt;/p&gt;&lt;p&gt;JRuby also lets you call Java libraries &lt;i&gt;not&lt;/i&gt; included in the standard set of class libraries associated with the Java Platform. By copying jars to &lt;tt&gt;$JRUBY_HOME/lib&lt;/tt&gt; or by modifying the CLASSPATH environment variable, you can access third-party Java libraries from JRuby scripts or from jirb, an interactive JRuby shell. It is also possible to add a jar to the classpath by requiring the jar (if it exists in the JRuby library load path):
&lt;pre name=&quot;code&quot; class=&quot;ruby&quot;&gt;
require 'whatever.jar'
com.whatever.Whatever.doSomething
&lt;/pre&gt;

&lt;/p&gt;&lt;h2&gt;&lt;a name='Related_Articles'&gt;&lt;/a&gt; Related Articles &lt;/h2&gt;
&lt;ul&gt;&lt;li&gt; &lt;a class='external' href=&quot;http://mikiobraun.blogspot.com/2008/11/java-integration-in-jruby.html&quot;&gt;Java Integration in JRuby&lt;/a&gt; Short overview article on JRuby and Java integration.
&lt;/li&gt;&lt;li&gt; &lt;a class='external' href=&quot;http://blogs.sun.com/sundararajan/entry/java_integration_javascript_groovy_and&quot;&gt;Java Integration: JavaScript, Groovy and JRuby&lt;/a&gt; Side-by-side comparison of Java integration in JavaScript, Groovy and JRuby.
&lt;/li&gt;&lt;li&gt; &lt;a class='external' href=&quot;http://jruby.codehaus.org/Java+Integration&quot;&gt;Java Integration&lt;/a&gt; From the JRuby main page.
&lt;/li&gt;&lt;li&gt; &lt;a class='external' href=&quot;http://jtestr.codehaus.org/&quot;&gt;JtestR&lt;/a&gt; A testing framework for Java based on JRuby.
&lt;/li&gt;&lt;li&gt; &lt;a class='external' href=&quot;http://github.com/leandrosilva/sparrow&quot;&gt;Sparrow&lt;/a&gt; A JMS client for messaging based on JRuby.
&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&lt;br /&gt;

&lt;/p&gt;</text-as-html>
  <updated-at type="datetime">2009-12-02T03:57:47Z</updated-at>
  <wiki-id type="integer">320</wiki-id>
</page>
