4

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.

Roy Tinker
  • 10,044
  • 4
  • 41
  • 58
holerd
  • 55
  • 1
  • 5

4 Answers4

8

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'

Community
  • 1
  • 1
Mark Thomas
  • 37,131
  • 11
  • 74
  • 101
1

If you have a Java class com.mypackage.MyClass in the same folder, or in a folder present on the classpath, you can call it from your JRuby script like this:

require 'java'
import com.pack.MyClass

myClass = MyClass.new

If the class is in a jar, you have to require the jar:

require 'java'
require '/path/to/myjar.jar'
import com.pack.MyClass

myClass = MyClass.new

If myjar.jar is on the classpath, you can just use require 'myjar.jar'.

Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
0

So Here is what worked for me, I had all required stuff that people suggested but what I really needed was

$CLASSPATH << (Rails.root.to_s + "/path/to/dotClassFolder")

before the java_import statement

so in the file system, if your class was was in the folder

Rails.root/path/to/dotClassFolder/folder/anotherFolder/MyClass.class

Include $CLASSPATH << (Rails.root.to_s + "/path/to/dotClassFolder") then java_import "folder.anotherFolder.MyClass"

See

From .class files section at https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby

Maged Makled
  • 1,918
  • 22
  • 25
0

Did you try include Java?

See this for more details: http://blogs.oracle.com/coolstuff/entry/using_java_classes_in_jruby

Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
ibz
  • 44,461
  • 24
  • 70
  • 86