2010/5/30 Jrg W Mittag <JoergWMittag+Ruby / googlemail.com>:
> JRuby (<http://JRuby.Org/>) started out as an interpreter, but it has
> both a JIT compiler and an AOT compiler
> (<https://GitHub.Com/JRuby/JRuby/tree/master/src/org/jruby/compiler/>)
> ('jrubyc') that can compile Ruby sourcecode to JVM bytecode ('.class'
> files). Also, work is underway to create a *new*
> (<https://GitHub.Com/JRuby/JRuby/blob/master/tool/compiler2.rb>)
> compiler that can compile (type-annotated) Ruby code to JVM bytecode
> that actually looks like a Java class and can be used from Java code
> without barriers.

This has largely landed in 1.5.1, with improvements to follow in 1.6 I'm sure.

The following Ruby code:

class Foo
  def initialize(a, b); @a, @b = a, b; end
  def foo(a); @a + a; end
  def self.bar(a); a * a; end
end

Compiles to this Java class (just outlined here):


~/projects/jruby  jrubyc --javac foo.rb
Generating Java class Foo to /Users/headius/projects/jruby/Foo.java
javac  -d /Users/headius/projects/jruby -cp
/Users/headius/projects/jruby/lib/jruby.jar:.
/Users/headius/projects/jruby/Foo.java

~/projects/jruby  javap Foo
Compiled from "Foo.java"
public class Foo extends org.jruby.RubyObject{
    public static org.jruby.runtime.builtin.IRubyObject
__allocate__(org.jruby.Ruby, org.jruby.RubyClass);
    public Foo(java.lang.Object, java.lang.Object);
    public java.lang.Object foo(java.lang.Object);
    public static java.lang.Object bar(java.lang.Object);
    static {};
}

Adding type signatures to appease Java:

require 'java'

class Foo
  java_signature "Foo(int, String)"
  def initialize(a, b); @a, @b = a, b; end
  java_signature "int foo(int)"
  def foo(a); @a + a; end
  java_signature "String bar(String)"
  def self.bar(a); a + a; end
end

Produces the following class:

Compiled from "Foo.java"
public class Foo extends org.jruby.RubyObject{
    public static org.jruby.runtime.builtin.IRubyObject
__allocate__(org.jruby.Ruby, org.jruby.RubyClass);
    public Foo(int, java.lang.String);
    public int foo(int);
    public static java.lang.String bar(java.lang.String);
    static {};
}

Fun and simple :)

- Charlie