Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
(ns apply-ctor
(import [java.lang.reflect Constructor]))
(defn- acceptable-types? [ptypes atypes]
(and (= (count ptypes) (count atypes))
(every? (fn [[ptype atype]]
(or (= ptype atype)
((ancestors atype) ptype)))
(map vector ptypes atypes))))
(defn apply-ctor [^Class klass args]
(let [atypes (into-array Class (map class args))
ctors (for [^Constructor ctor (.getConstructors klass)
:let [ptypes (.getParameterTypes ctor)]
:when (acceptable-types? ptypes atypes)]
ctor)]
(when (empty? ctors)
(throw (IllegalArgumentException.
(str "No matching ctor found for " klass))))
(let [^"[Ljava.lang.Object;" args (into-array Object args)]
(.newInstance ^Constructor (first ctors) args))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment