2012-07-28 53 views
33

我把一個java lib包裝到clojure中,但是我在處理變長參數時遇到了問題。假設,如何在clojure中處理java變量長度參數?

TestClass.aStaticFunction(Integer... intList){/*....*/} 

我怎麼能在clojure中調用這個函數?

+0

可能重複http://stackoverflow.com/questions/9103777/implement-a-java-interface-method-with-a -variable用戶號碼-ARGS功能於Clojure中的) – Jeremy 2012-07-28 15:41:33

回答

39

由於Java的可變參數是actually arrays,你可以通過一個數組來調用Clojure中的可變參數的功能。

你可以轉換一個Clojure的序列(可能通過使用Clojure的各種變量參數函數)到一個數組:

(TestClass/aStaticFunction (into-array Integer [(int 1),(int 2)])) 

(defn a-static-function-wrapper [& args] 
    (TestClass/aStaticFunction (into-array Integer args)) 

或進行排列,並手動設置其指數

(TestClass/aStaticFunction (doto (make-array Integer 3) 
           (aset 0 first-element) 
           (aset 1 second-element) 
           (aset 2 third-element))) 
+1

'整數/ TYPE'將創建一個基本數組,這可能不是什麼這裏想....懷疑你只想'Integer'。 – mikera 2012-07-28 15:29:51

+0

@mikera我也需要原始數組!非常感謝你! – qiuxiafei 2012-07-28 15:46:48

5

爪哇可變長度參數需要的是一個數組作爲輸入。

所以在Clojure的通話應該是這樣的:

(TestClass/aStaticFunction (into-array Integer some-sequence-of-integers)) 
4
(TestClass/aStaticFunction (to-array '(1 2 3 4 5))) 

對於例如

(java.util.Arrays/asList (to-array '(1 2 3 4 5))) 
的[實施與參數的個數Clojure中的可變數量的Java接口方法](
相關問題