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.

5 thoughts on “Call a JRuby method from Java

  1. badi

    Hi Tommy,
    A question. Pastedroid is down, a tool which I use daily… Are you going to continue supporting it?
    Greetings,
    Badi

    Reply
      1. badi

        Yup, the new link is working! Thanks. The description on the android market (or google play) points to pastedroid.com so you will probably want to update that.

  2. Pingback: Learning about Servers | Will's Apprenticeship at 8th Light

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s