Tommy Chheng

Icon

All Things Programming!

Call a JRuby method from Java

JRuby is a great way of reducing verbose Java code. Here’s a way of implementing a Java interface in JRuby and calling the method from Java.

Java Interface

We’ll start with a simple Java interface:


interface JavaInterfaceExample{
  int add(int a, int b);
}

Compile it using

javac JavaInterfaceExample.java

Implement the Java Interface in JRuby

We will implement this method in JRuby. When importing interfaces from Java code, you should use the Java namespace as in include Java::JavaInterfaceExample. The signature is important since JRuby is dynamically typed. If it isn’t specified, the parameters will be a Java Object.


require 'java'
class JrubyAdderImpl
  include Java::JavaInterfaceExample
  java_signature 'int add(int, int)'
	def add(a, b)
		a+b
	end
end

Compile it using:

jrubyc --javac -cp . JrubyAdderImpl.rb

Creating a Java class calling a JRuby method

Then let’s create a Java class which calls the jruby method:


class JavaCallerApp {
    public static void main(String[] args) {
	    JrubyAdderImpl jrubyImpl = new JrubyAdderImpl();
	    System.out.println("Adding 3+5=" + jrubyImpl.add(3,5)); // Display the string.
    }
}

Compile it:

javac -cp /usr/local/jruby/lib/jruby.jar:. JavaCallerApp.java

and run it:

java -cp /usr/local/jruby/lib/jruby.jar:. JavaCallerApp

Output:

Adding 3+5=8

Downside

While this works, it’s not a very optimally solution for calling JRuby code from Java. When you compiled JrubyAdderImpl.rb, it created a JrubyAdderImpl.java file which runs a JRuby runtime layer against the JRuby script file. I imagine this isn’t very performant.

I recommend using Mirah or Scala as alternative JVM languages for greater interoperability with Java.

I placed the code on a github repo.

Read Books on the Amazon Kindle 3