When I compile a ruby file to a java class using jrubyc
, I get different output when compiling with just jrubyc
and with jrubyc --java
(to generate the java file) and just javac
. Why?
Example:
First method:
jrubyc --java myscript.rb
javac -cp .:./jruby-complete.jar myscript.java
Second Method:
jrubyc myscript.rb
I'd expect the generated classes to be exactly the same, but they're not. What's jrubyc
doing under the covers?
Thanks!
jrubyc myscript.rb
compiles the Ruby file for JRuby consumption and cannot be used from Java, hence the name AOT. The code used to compile it is the normal JRuby compiler that's used to transform to bytecode. You can only use the resultingmyscript.class
in a JRuby script, using for instancerequire 'myscript'
. When usingjavap
:we see the extended class inherits
org.jruby.ast.executable.AbstractScript
and defines lots of internal methods, so it is clear this code is for JRuby's AST use.That's why
jrubyc
provides two extra options:--java
and--javac
: the first one generates the Java source code that wraps the code to the JRuby script usingScriptingContainer
, just as you normally would with the original script; the second one produces directly the compiled Java class directly. This code uses specific Java generator code that uses directives such asjava_signature
to give the Java methods the correct signatures as expected by Java. When usingjavap
again:the class starts with an uppercase M, and inherits
RubyObject
. Methods defined in the class will be exposed for Java consumption.Using JRuby: Bringing Ruby to Java has a good description of these two forms in Chapter 4, The JRuby Compiler.