PageRenderTime 51ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/ehcache/src/clj_cache/bean.clj

https://github.com/bmabey/clj-cache
Clojure | 58 lines | 37 code | 7 blank | 14 comment | 3 complexity | b50150038bbcca0fe86d7af4edcfffde MD5 | raw file
  1. ;; Copyright (c) Justin Balthrop. All rights reserved. The use and
  2. ;; distribution terms for this software are covered by the Eclipse Public
  3. ;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
  4. ;; be found in the file epl-v10.html at the root of this distribution. By
  5. ;; using this software in any fashion, you are agreeing to be bound by the
  6. ;; terms of this license. You must not remove this notice, or any other
  7. ;; from this software.
  8. ;;
  9. ;; bean.clj
  10. ;;
  11. ;; Modify bean attributes in clojure. Inspired by lancet.
  12. ;;
  13. ;; code@justinbalthrop.com
  14. ;; Created July 6, 2010
  15. (ns
  16. #^{:author "Justin Balthrop"
  17. :doc "Modify bean attributes in clojure."}
  18. clj-cache.bean
  19. (:import [java.beans Introspector]))
  20. (defn- property-key [property]
  21. (keyword (.. (re-matcher #"\B([A-Z])" (.getName property))
  22. (replaceAll "-$1")
  23. toLowerCase)))
  24. (defn property-setters
  25. "Returns a map of keywords to property setter methods for a given class."
  26. [class]
  27. (reduce
  28. (fn [map property]
  29. (assoc map (property-key property) (.getWriteMethod property)))
  30. {} (.getPropertyDescriptors (Introspector/getBeanInfo class))))
  31. (defmulti coerce (fn [bean-class type val] [type (class val)]))
  32. (defmethod coerce :default [_ type val]
  33. (cond
  34. (= String type) (str val)
  35. (= Integer/TYPE type) (Integer. val)
  36. :else (try (cast type val)
  37. (catch ClassCastException e
  38. val))))
  39. (use 'clojure.pprint)
  40. (defn update-bean
  41. "Update the given bean instance with attrs by calling the appropriate setter methods on it."
  42. [instance attrs]
  43. (let [bean-class (class instance)
  44. setters (property-setters bean-class)]
  45. (doseq [[key val] attrs]
  46. (if-let [setter (setters key)]
  47. (when-not (nil? val)
  48. (let [type (first (.getParameterTypes setter))]
  49. (.invoke setter instance (into-array [(coerce bean-class type val)]))))
  50. (throw (Exception. (str "property not found for " key)))))
  51. instance))