Reputation: 1005
So, I've started out with Java and having some trouble loading a class in a JRuby script, or in another Java app. Let's use this file as an example:
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();
}
}
When i compile it in NetBeans, it makes a jar file with that class file in it, and a META-INF file. I can require it in JRuby, but i can't do the java_import part:
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'))
Upvotes: 4
Views: 380
Reputation: 1005
Still upvoting, but found it out myself, i just need to do
Java::dice.Dice
because, it only works without the Java::
part when it is in the java folder of packages like
java.lang.System
Upvotes: 0
Reputation: 1121
Because of package statement I put dice inside of dir dice, and compiled it.
.
└── dice
├── Dice.class
└── Dice.java
Run IRB
$ irb
We need to add the classpath to Jruby and import using package prefix
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>
Upvotes: 2