因此,我开始使用Java时遇到了一些麻烦,无法在JRuby脚本或另一个Java应用程序中加载类。让我们以该文件为例:
package dice;
import java.util.Random;
public class Dice {
public int sides;
private Random random;
public Dice(int sides) {
this.sides = sides;
this.random = new Random();
}
public Dice() {
this.sides = 6;
this.random = new Random();
}
}
当我在NetBeans中编译它时,它将生成一个其中包含该类文件的jar文件以及一个META-INF文件。我可以在JRuby中要求它,但是我不能执行java_import部分:
irb(main):013:0> java.dice.Dice
Traceback (most recent call last):
7: from C:/jruby-9.2.4.1/bin/jirb:13:in `<main>'
6: from org/jruby/RubyKernel.java:1181:in `catch'
5: from org/jruby/RubyKernel.java:1181:in `catch'
4: from org/jruby/RubyKernel.java:1415:in `loop'
3: from org/jruby/RubyKernel.java:1043:in `eval'
2: from (irb):13:in `evaluate'
1: from org/jruby/javasupport/JavaPackage.java:252:in `method_missing'
NameError (missing class name (`java.dice.Dice'))
答案 0 :(得分:2)
由于package语句,我将Dice放在dir Dice中,并对其进行了编译。
.
└── dice
├── Dice.class
└── Dice.java
运行IRB
$ irb
我们需要将类路径添加到Jruby并使用包前缀导入
jruby-9.2.0.0 :001 > $CLASSPATH << "."
jruby-9.2.0.0 :002 > java_import 'dice.Dice'
=> [Java::Dice::Dice]
jruby-9.2.0.0 :003 > Dice.new
=> #<Java::Dice::Dice:0x4f9a3314>
答案 1 :(得分:0)
仍然投票,但我自己发现了,我只需要这样做
Java::
因为,只有当它位于软件包之类的java文件夹中时,它才没有java.lang.System
部分才能工作
{{1}}