tags:

views:

116

answers:

2

I can't seem to find what the current syntax for using java classes in Jruby is. This link text article lists:

include Java
include 'java'
require 'java'

As valid options, though it says the last option is pre 1.0 and doesn't work.
The Jruby Wiki however says to use require 'java'

And for including classes I've seen

MyClass = Java::some.package.MyClass
include_class Java::some.package.MyClass
include_class 'some.package.MyClass'
java_import Java::some.package.MyClass

Is there one preferred method?

Currently I'm getting some "redefining X" message as I have a few java classes named the same as my ruby class. What's the best method for keeping the java namespace so I don't get these, and are there any issues (aside from the obvious Java class taking precedent to the ruby class) with this redefinition if I never use the two ruby/java classes in the same file?

+1  A: 

Personally, I always use require 'java'

If you're having namespace clashes, I'd suggest not including or importing, but specifying fully qualified class names, e.g.

my_instance = Java::JavaUtil::Date.new

...where Java:: is top level module for all java classes, JavaUtil:: is the full package name for the class I want, in proper-case and jammed together, and Date is the actual class name.

Rob
A: 

I prefer

require 'java'
java_import java.lang.System

I think the choice of require 'java' is not that import and is just personal preference. On the other hand, JRubyWiki says java_import is preferred, due to this bug report.

For the name conflict between Java and JRuby classes. For the sake of code readability or for maintenance purpose, I'd suggest to avoid using the same Name for 2 different classes, unless you mean to re-open it.

Update: are you sure the error 'Redefine X ...' is caused by having the same name for your Java and JRuby class? I usually get this error because I java_import the same Java class multiple times (sometimes in different places, sometime I load the same file multiple times).

bryantsai
hmm... never thought about that, I'll check it out, thx
brad
ya it appears to be clashing. When I instantiate an object that includes a bunch of java classes (only once) I get that message. I have a ruby "Supplier" class and I also include a "new.my_app.Supplier" java class with include_class
brad