On Tue, Jan 10, 2012 at 22:46 +0000, Norman Gray wrote: > I've run into a situation which (I think) is the Clojure analogue of > <http://stackoverflow.com/questions/5672778/class-getmethod-when-parameter-is-varargs>, > and I'm not sure how to apply the solution there to Clojure (I'm a Clojure > beginner, though familiar with Java and with various Schemes). > > That is, I want to call a Java method with varargs and , if I'm > understanding my problem correctly, (a) I can't do so straightforwardly > using '.' in Clojure, and (b) I can't work out how to call .getMethod > correctly.
I've stumbled over varargs in Clojure before and Alan Malloy came up with a
nice solution [0] which I expanded slightly:
--- snip ---
(defmacro real-varargs [method required-count & array-type]
(let [args (repeatedly (inc required-count) gensym)]
`(let [f# (fn [~@args]
(~method ~@args))]
(fn [& args#]
(let [[before# after#] (split-at ~required-count args#)]
(apply f# `(~@before# ~(into-array ~@array-type after#))))))))
user> (def add-all (real-varargs java.util.Collections/addAll 1))
#'user/add-all
user> (seq (doto (java.util.ArrayList.) (add-all "10" "20")))
("10" "20")
user> (def add-all (real-varargs java.util.Collections/addAll 1 String))
#'user/add-all
user> (seq (doto (java.util.ArrayList.) (add-all "10" "20")))
("10" "20")
--- snip ---
Hope you find it as useful as I :)
[0] https://gist.github.com/1440296
--
Wolodja <[email protected]>
4096R/CAF14EFC
081C B7CD FF04 2BA9 94EA 36B2 8B7F 7D30 CAF1 4EFC
signature.asc
Description: Digital signature
