开发者

Using Custom Java Class file in Jruby

I am trying to execute some c开发者_如何学Goustom 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.


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'


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'.


Did you try include Java?

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜