I want to pass a Java class to a JRuby method, and instantiate the class object in the method (I want a generic way of running some tests on a set of Java classes, and also need to instantiate a number of these objects, not known until runtime):
#...
somethingMethod(Bar)
#....
def somethingMethod(javaClass)
number.each do |n|
fu=javaClass.new
#...otherStuff
end
end
But this does not seem to be doable in this fashion. I get:
Failure/Error: somethingMethod(Bar)
NameError:
uninitialized constant Bar
# somethingTest.rb:45:in `(root)'
I've also tried to use the fully qualified class name: same results. Thanks.
For this, use java_class attribute of the JRuby wrapped class.
In your code
javaClass.java_class.new
should work.
You should also use this attribute, when Java method expects Java class as a parameter.
For more examples, see https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby
This works fine for me--are you importing the class? Requiring "java"?
jruby-1.6.2 :001 > def foo(c)
jruby-1.6.2 :002?> cc = c.new
jruby-1.6.2 :003?> puts ">>#{cc}<<"
jruby-1.6.2 :004?> end
jruby-1.6.2 :005 > foo(String)
>><<
jruby-1.6.2 :007 > foo(ArrayList)
NameError: uninitialized constant ArrayList
jruby-1.6.2 :008 > foo(java.util.ArrayList)
jruby-1.6.2 :009 > require 'java'
jruby-1.6.2 :010 > foo(java.util.ArrayList)
>>[]<<
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.