Skip to content

Instantly share code, notes, and snippets.

@jcromartie
Created February 27, 2011 04:39
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 jcromartie/845906 to your computer and use it in GitHub Desktop.
Save jcromartie/845906 to your computer and use it in GitHub Desktop.
(ns rec-print)
(defn rec-pr-str
"Print record to string with type information"
[r]
(let [class-name (.getName (class r))]
(pr-str (merge {::rec-class class-name} r))))
(def lookup-class
(memoize
(fn
[class-name]
(Class/forName class-name))))
(defn rec-read-string
"(re)create record from rec-pr-str string using reflection"
[s]
(let [m (read-string s)
class (lookup-class (::rec-class m))
ctor (first (.getDeclaredConstructors class))
arity (count (.getParameterTypes ctor))
base-map (dissoc m ::rec-class)
base-record (.newInstance ctor (make-array Object arity))]
(merge base-record base-map)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment