Java – RJB Hello World example

RJB Hello World example… here is a solution to the problem.

RJB Hello World example

I’m trying to call a function using RJB (Ruby Java Bridge) from a java class in my Ruby on Rails project.

The Java class is

public class HelloWorld {

int fifty(){
        return 50 ;
    }
   public static void main(String[] args) {
       Prints "Hello, World" in the terminal window.
      System.out.println("Hello, World");
   }
}

In my Controller

  require "rjb"
  def home
      myclass = Rjb::load(classpath ='\\home\\mennatallah\\TopicalClusteringofTweets\\lib\\java_libs\\helloworld.class', jvmargs=[])

myclass_instance = myclass.new
      @output =   myclass_instance.fifty
  end

It provides “undefined method ‘new'” for nil:NilClass
What should I do?

Solution

You can try the following. It might help:

Rjb::add_jar( Dir.glob("#{Rails.root}/lib/java_libs/*.jar").join(':'))
Rjb::load(Dir.glob("#{Rails.root}/lib/java_libs/*.jar").join(':'))
test = Rjb.import('HelloWorld')
instance_class  = test.new

Related Problems and Solutions