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.

4 Answers 4

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'

Sign up to request clarification or add additional context in comments.

2 Comments

this solution still doesn't work for me. Do I need to compile the custom class in some way to make it load?
I added some more examples to that wiki link, in case helpful.
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'.

Comments

0

Did you try include Java?

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.