0

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

The problem was I was using com.foo.Bar instead of com::foo::Bar to fully qualify the class name (!). And javaClass.java_class.new did not work: Failure/Error: somethingMethod(com::foo::Bar) NoMethodError: undefined method new for class com.foo.Bar::JavaClass
0

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)
>>[]<<

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.