Search code examples
rubyrjb

How to import classes with Ruby Java Bridge


I have a jar file that has a class that I would like to use from my Rails project. I have tried to import the class with Rjb with these commands. The jar file is in the bin directory.

Rjb.load("#{Rails.root}/bin")
=> nil
Rjb::add_jar("excel_tools.jar")
=> true
Rjb::import("tools.CellEditor")
ClassNotFoundException: tools.CellEditor
Rjb::import("tools/CellEditor")
ClassNotFoundException: tools.CellEditor

The class name "tools.CellEditor" should be correct. At least when I list the classes in the jar in terminal I get this and many more classes from apache poi and log4j.

$ jar tvf bin/excel_tools.jar
6926 Mon Aug 25 13:24:00 EEST 2014 tools/CellEditor.class

Any idea where the jar or class loading goes wrong?


Solution

  • I got this working by importing all the jar files my java class depends on. It is not enough that the dependence jars are bundled into another jar file with my class, they need to be loaded separately before importing the class it self.

    I copied all the jars into a java_libs directory and wrote an initializer like this

    require 'rjb'
    
    JARS = Dir.glob("#{Rails.root}/lib/java_libs/*.jar").join(':')
    Rjb::load(JARS)
    CELL_EDITOR = Rjb::import('tools.CellEditor')
    

    Now I can use the CELL_EDITOR methods anywhere in my code.