简体   繁体   English

将Java类作为参数传递给JRuby方法

[英]Passing Java class as argument to JRuby method

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): 我想将Java类传递给JRuby方法,并实例化该方法中的类对象(我想以一种通用的方式在一组Java类上运行一些测试,并且还需要实例化其中一些对象,这是未知的直到运行):

#...
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. 为此,请使用JRuby包装的类的java_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. 当Java方法希望将Java类作为参数时,也应该使用此属性。

For more examples, see https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby 有关更多示例,请参见https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby

This works fine for me--are you importing the class? 这对我来说很好-您正在导入课程吗? Requiring "java"? 需要“ 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)
>>[]<<

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM