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