What is a way to “require” Java package that is not packed into JAR?
From my point of view I could expect something like follow to work:
include Java
require ‘/mypath/project1/bin’
java_import ‘com.my.package.MyClass’
where project1 is something built by Eclipse or NetBeans, without
generating project1.jar each time.
Unfortunately, my guess is wrong. At least with JRuby 1.1.5.
JRuby.runtime.jruby_class_loader.addURL( … )
Seems good enough for me.
However, the follow error is printed:
(eval):1:in include_class': cannot load Java class com.my.pkg.MyClass (NameError) from file:/C:/JRuby/jruby-1.1.5/lib/jruby.jar!/builtin/javasupport/core_ext/object.rb:38:ineval’
from
file:/C:/JRuby/jruby-1.1.5/lib/jruby.jar!/builtin/javasupport/core_ext/object.rb:67:in include_class' from file:/C:/JRuby/jruby-1.1.5/lib/jruby.jar!/builtin/javasupport/core_ext/object.rb:38:ineach’
from
file:/C:/JRuby/jruby-1.1.5/lib/jruby.jar!/builtin/javasupport/core_ext/object.rb:38:in include_class' from file:/C:/JRuby/jruby-1.1.5/lib/jruby.jar!/builtin/javasupport/core_ext/object.rb:81:injava_import’
from r1.rb:4
“require ‘project1.jar’” works fine with the same sources.
The sample sources are attached.
$CLASSPATH << ‘/path/to/my/classes’
The $CLASSPATH << ‘/path’ part works, however the error remains the
same:
“(eval):1:in `include_class’: cannot load Java class com.my.pkg.MyClass”
and points into “java_import ‘com.my.pkg.MyClass’”.
After some extensive testing, the follow syntax works:
JRuby.runtime.getJRubyClassLoader.addURL(Java::java.net.URL.new(path))
java_import ‘com.my.pkg.MyClass’
To summarize, it’s all related to Java’s URLClassLoader
This class loader is used to load classes and resources from a search
path of URLs referring to both JAR files and directories. Any URL that
ends with a ‘/’ is assumed to refer to a directory. Otherwise, the URL
is assumed to refer to a JAR file which will be opened as needed.