Question

I am trying to import a Java Class in Jruby

$ ls
bin src

$ ls bin/com/practice
Test.class

$ ls src/com/practice
Test.java

$ cat src/com/practice/Test.java
package com.practice;

public class Test {
    public static String foo(){
        return "Java!!";
    }

    public static void main(String args[]){
        System.out.println(Test.foo());
    }
}
$ jirb -Ibin
jruby-1.7.10 :001 > java_import 'com.pratice.Test'
NameError: cannot load Java class com.pratice.Test
    from org/jruby/javasupport/JavaClass.java:1250:in `for_name'
    from org/jruby/javasupport/JavaUtilities.java:34:in `get_proxy_class'
    from file:/Users/gaurish/.rvm/rubies/jruby-1.7.10/lib/jruby.jar!/jruby/java/core_ext/object.rb:26:in `java_import'
    from org/jruby/RubyArray.java:2409:in `map'
    from file:/Users/gaurish/.rvm/rubies/jruby-1.7.10/lib/jruby.jar!/jruby/java/core_ext/object.rb:22:in `java_import'
    from (irb):1:in `evaluate'
    from org/jruby/RubyKernel.java:1119:in `eval'
    from org/jruby/RubyKernel.java:1519:in `loop'
    from org/jruby/RubyKernel.java:1282:in `catch'
    from org/jruby/RubyKernel.java:1282:in `catch'
    from /Users/gaurish/.rvm/rubies/jruby-1.7.10/bin/jirb:13:in `(root)'

What am I doing wrong here?

Was it helpful?

Solution

You have a number of problems:

  1. You've misspelled "practice" in irb: java_import 'com.pratice.Test'
  2. Your class isn't actually in the correct package. You need to add package com.practice; to the Java code.
  3. You need to add "bin" to your classpath so that the JVM can find the classes: $CLASSPATH << 'bin'

Altogether, I was able to run this in IRB:

$CLASSPATH << 'bin'
com.practice.Test.foo
# => "Java!!"

EDIT: I failed to copy your package line, that's my fault, not yours. :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top