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


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)

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:.

and run it:

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


Adding 3+5=8


While this works, it’s not a very optimally solution for calling JRuby code from Java. When you compiled JrubyAdderImpl.rb, it created a 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?

      1. badi

        Yup, the new link is working! Thanks. The description on the android market (or google play) points to 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: Logo

You are commenting using your 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