I finally got around to writing an "unbean" function. As the name
suggests, it's the reverse of the bean function: it takes a class and
a map of property name/values and returns an instance of that class
with those property values. So for example, if class House has
properties "address", "color", and "area", you can do this:
user=> (def h (unbean House {:address "100 Elm Street" :color
"red" :area 2500}))
#'user/h
user=> (.getAddress h)
"100 Elm Street"
user=> (bean h)
{:address "100 Elm Street", :color "red", :area 2500}
user=>
Questions:
1. It's a real function, not a macro, and it uses reflection, so it's
not something you would want to use in a tight loop. Would a macro be
more appropriate?
2. Would this kind of thing be a useful addition to the core API?
Here's the code:
(defn unbean [clazz props]
(let [x (.newInstance clazz)
pmap (reduce (fn [m pd]
(let [name (.getName pd)
method (.getWriteMethod pd)]
(if (and method (= 1 (alength (. method
(getParameterTypes)))))
(assoc m (keyword name) (fn [v] (. method (invoke x
(into-array
[v])))))
m)))
{}
(.getPropertyDescriptors
(java.beans.Introspector/getBeanInfo
clazz)))]
(doseq [kv props]
(((keyword (first kv)) pmap) (second kv)))
x))
Bill Smith
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---