Search code examples
jruby

jruby cannot load Java class com.example.CallMe


I am new to jruby. I was trying to run sample programs given on their github wiki. https://github.com/jruby/jruby/wiki/JRubyAndJavaCodeExamples#JRuby_calling_Java

My directory structure is :

D:\learnJruby\CallJava.rb
D:\learnJruby\com\example\CallMe.java
D:\learnJruby\com\example\ISpeaker.java

When I run

jruby CallJava.rb

I am getting this error

NameError: cannot link Java class com.example.CallMe, probable missing dependency: com/example/CallMe (wrong name: CallMe)
         for_name at org/jruby/javasupport/JavaClass.java:1286
  get_proxy_class at org/jruby/javasupport/JavaUtilities.java:34
      java_import at file:/C:/jruby-1.7.16/lib/jruby.jar!/jruby/java/core_ext/object.rb:26
              map at org/jruby/RubyArray.java:2412
      java_import at file:/C:/jruby-1.7.16/lib/jruby.jar!/jruby/java/core_ext/object.rb:22
           (root) at CallJava.rb:4


Solution

  • Java is compiling language then you need compile your .java files (source code) to .class files (JVM bytecode) before run it.

    When you run Java it looks for .class files in directories and .jars from classpath.

    You can require classes explicitly from JRuby:

    • require 'some.jar'

    • $CLASSPATH << "target/classes"; java_import org.asdf.ClassName

    https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby#accessing-and-importing-java-classes

    And one more advice - don't use java_import outside of class or module because java class will be imported to global scope (Object class):

    require 'java'
    require 'foo.jar'
    
    java_import 'foo.bar.Foo' # Bad! Foo is global constant now
    
    module Bar
      java_import 'foo.bar.Baz' # good, Baz is constant in module Bar, e.g. Bar::Baz
    end