1

我正在尝试在 Jruby 中导入 Java 类

$ 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)'

我在这里做错了什么?

4

1 回答 1

4

你有很多问题:

  1. 你在 irb 中拼错了“practice”:java_import 'com.pratice.Test'
  2. 您的课程实际上不在正确的包中。您需要添加package com.practice;到 Java 代码中。
  3. 您需要将“bin”添加到类路径中,以便 JVM 可以找到这些类:$CLASSPATH << 'bin'

总之,我能够在 IRB 中运行它:

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

编辑:我没有复制你的package线路,这是我的错,不是你的。:-)

于 2014-03-09T16:59:08.990 回答