view src/clojure/test_clojure/annotations/java_5.clj @ 10:ef7dbbd6452c

added clojure source goodness
author Robert McIntyre <rlm@mit.edu>
date Sat, 21 Aug 2010 06:25:44 -0400
parents
children
line wrap: on
line source
1 ;; java 5 annotation tests
2 (in-ns 'clojure.test-clojure.annotations)
4 (import [java.lang.annotation Annotation Retention RetentionPolicy Target ElementType])
5 (definterface Foo (foo []))
7 (deftype #^{Deprecated true
8 Retention RetentionPolicy/RUNTIME}
9 Bar [#^int a
10 #^{:tag int
11 Deprecated true
12 Retention RetentionPolicy/RUNTIME} b]
13 Foo (#^{Deprecated true
14 Retention RetentionPolicy/RUNTIME}
15 foo [this] 42))
17 (defn annotation->map
18 "Converts a Java annotation (which conceals data)
19 into a map (which makes is usable). Not lazy.
20 Works recursively. Returns non-annotations unscathed."
21 [#^java.lang.annotation.Annotation o]
22 (cond
23 (instance? Annotation o)
24 (let [type (.annotationType o)
25 itfs (-> (into #{type} (supers type)) (disj java.lang.annotation.Annotation))
26 data-methods (into #{} (mapcat #(.getDeclaredMethods %) itfs))]
27 (into
28 {:annotationType (.annotationType o)}
29 (map
30 (fn [m] [(keyword (.getName m)) (annotation->map (.invoke m o nil))])
31 data-methods)))
32 (or (sequential? o) (.isArray (class o)))
33 (map annotation->map o)
34 :else o))
36 (def expected-annotations
37 #{{:annotationType java.lang.annotation.Retention, :value RetentionPolicy/RUNTIME}
38 {:annotationType java.lang.Deprecated}})
40 (deftest test-annotations-on-type
41 (is (=
42 expected-annotations
43 (into #{} (map annotation->map (.getAnnotations Bar))))))
45 (deftest test-annotations-on-field
46 (is (=
47 expected-annotations
48 (into #{} (map annotation->map (.getAnnotations (.getField Bar "b")))))))
50 (deftest test-annotations-on-method
51 (is (=
52 expected-annotations
53 (into #{} (map annotation->map (.getAnnotations (.getMethod Bar "foo" nil)))))))