Using Custom Java Class file in Jruby

holerd picture holerd · Jun 30, 2010 · Viewed 7.1k times · Source

I am trying to execute some custom Java code through the latest version of Jruby (1.5.1), Ruby 1.8.7, with Java 1.6.0_06. I have tried both the class file and putting it in a jar method. When I try

require 'java'  
require 'path_to_class/myClass

or

require 'java'  
require 'path_to_jar/a_jar.jar  

Trying both methods, I cannot access the myClass nor any other files in the jar file. Other variations on the net for importing java classes lead to the following error:

`NameError: cannot load Java class com.package.myClass from C:/jruby-1.5.1/lib/ruby/site_ruby/shared/builtin/javasupport/java.rb:51:in method_missing`

I have also checked the solutions on StackOverFlow and I still get the same outcome. I am wondering if this might be a problem at a deeper level.

Answer

Mark Thomas picture Mark Thomas · Feb 5, 2011

Instead of 'require', you want 'java_import'.

require 'java'
java_import com.package.MyClass

See JRuby: import vs include vs java_import vs include_class for some more discussion e.g. why you should use 'java_import' instead of just 'import'