I tried to create a small example, where I invoke a method on a Java object, but I JRuby can't find the method.
I have the following file:
File t.java with content
class T {
public T() {}
public String f() {
return "abc";
}
}
I then do (inside the directory of t.java):
javac t.java # Produces a file T.class
jruby -e 'java_import "T"; r=T.new; puts(r.f)'
this produces the error message
NoMethodError: undefined method `f' for #Java::Default::T:0x38cee291
Interestingly, the constructor (T.new
) seems to have succeeded. Why can't I call the instance method f
?
Platform:
MacOS 12.6.5
jruby 9.4.3.0 (3.1.4) 2023-06-07 3086960792 Java HotSpot(TM) 64-Bit Server VM 25.341-b10 on 1.8.0_341-b10 +jit [x86_64-darwin]
I found, that the problem is on the Java side:
First, the class T
needs to be declared public. I don't know why I can create an instance of a non-public class, but can't call instance methods of it. This seems to be a Java-restriction.
Second, after renaming, the Java compiler insists that I also rename the file from t.java
to T.java
. The file name must match the class name.
After these changes, the example works.