Skip to content

Instantly share code, notes, and snippets.

@astrangeguy
Created February 24, 2010 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astrangeguy/313601 to your computer and use it in GitHub Desktop.
Save astrangeguy/313601 to your computer and use it in GitHub Desktop.
(import '[java.lang.reflect Field Modifier])
(defn private-fields [obj]
(let [obj-class (class obj)
public (set (.getFields obj-class))
all (seq (.getDeclaredFields obj-class))
fields (->> all
(remove public)
(remove #(Modifier/isStatic
(.getModifiers %))))]
(doseq [#^Field field fields]
(.setAccessible field true))
(map #(.get #^Field % obj) fields)))
(defmethod print-dup clojure.lang.Fn [f w]
(print-ctor f
(fn [o #^java.io.Writer w]
(doseq [field (private-fields o)]
(print-dup field w)
(.write w " ")))
w))
;; example
user> (let [a 5 b 6 f +]
(def serialized-fn (with-out-str
(print-dup (fn [c] [a b c (f a b c)]) *out*))))
#'user/serialized-fn
user> ((read-string serialized-fn) 1)
[5 6 1 12]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment