Call your Java method from your Ruby class

by kengilmer

This should have been really simple but the documentation I found on the net was overly verbose and didn’t really just give me what I wanted.  I had to read the text.  <gasp>  So for reference here is how to call your own Java code from your own Ruby code:

The ruby class that will start everything:

require 'java'
require '/tmp/java.jar'

class Main
  def run
    sayObj = Java::Talker.new()
    sayObj.say()
  end
end

app = Main.new
app.run
Before this will work we need to make a jar with our Java library.  It’s also possible to reference class files which can be handy when you’re running from an IDE and want updates to Java stuff to just work when being called from Ruby, by relying on the compile-while-edit feature of the IDE.  For us though let’s just keep it simple with a Jar.  I have a class called Talker.java with a default package:
public class Talker {

	public void say() {
		System.out.println("oh hi!");
	}
}
After making a jar and putting it in /tmp, you should be able to run the ruby command (using JRuby of course) on the command line…
$ jruby Main.rb
oh hi!
Advertisements