2012-01-10 70 views
0

我想將Java類傳遞給JRuby方法,並在方法中實例化類對象(我想要一種在一組Java類上運行某些測試的通用方法,需要實例化一個數量的這些對象,直到運行時才知道)的:將Java類作爲參數傳遞給JRuby方法

#... 
somethingMethod(Bar) 
#.... 

def somethingMethod(javaClass) 
    number.each do |n| 
    fu=javaClass.new 
    #...otherStuff 
    end 
end 

但這似乎並沒有被這種方式是可行的。我得到:

Failure/Error: somethingMethod(Bar) 
    NameError: 
     uninitialized constant Bar 
    # somethingTest.rb:45:in `(root)' 

我也試過使用完全合格的類名:相同的結果。 謝謝。

回答

1

爲此,請使用JRuby包裝類的java_class屬性。

在你的代碼

javaClass.java_class.new 

應該工作。

當Java方法需要Java類作爲參數時,您還應該使用此屬性。

更多的例子,請參閱 https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby

+0

問題是我使用com.foo.Bar而不是com :: foo :: Bar來完全限定類名(!)。和'javaClass.java_class.new'確實沒有**工作:'失敗/錯誤:somethingMethod(com :: foo :: Bar) NoMethodError: 未定義的方法new for com.foo.Bar::JavaClass' – ggg 2012-01-10 16:29:53

+0

謝謝! :-) – ggg 2012-01-10 16:35:21

0

這工作得很好,我 - 你導入類?需要「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) 
>>[]<< 
相關問題