2 * Copyright 2005-2010 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.reflection;
18 import java.lang.annotation.ElementType;
19 import java.lang.annotation.Retention;
20 import java.lang.annotation.RetentionPolicy;
21 import java.lang.annotation.Target;
22 import java.util.List;
24 import org.junit.Test;
26 import static junit.framework.TestCase.*;
28 public class AnnotationUtilsTest {
30 @Retention(RetentionPolicy.RUNTIME)
31 @Target( { ElementType.FIELD, ElementType.METHOD })
32 public static @interface MyAnnotation {
36 public static class X1 {
41 public static class X2 {
47 public static class X3 {
50 public void setX(int aX) {
60 public static class X4 {
63 private void setX(int aX) {
73 public static class X5 {
79 private void setX(int aX) {
90 public void testPublicField() {
91 List<Accessor> accessors = AnnotationUtils.analyse(X1.class,
93 assertEquals(1, accessors.size());
94 assertTrue(accessors.get(0) instanceof FieldAccessor);
95 assertEquals(int.class, accessors.get(0).getType());
98 assertEquals(0, obj.x);
99 accessors.get(0).set(obj, 100);
100 assertEquals(100, obj.x);
104 public void testPrivateField() {
105 List<Accessor> accessors = AnnotationUtils.analyse(X2.class,
107 assertEquals(1, accessors.size());
108 assertTrue(accessors.get(0) instanceof FieldAccessor);
110 assertEquals(0, obj.x);
111 accessors.get(0).set(obj, 100);
112 assertEquals(100, obj.x);
116 public void testPublicProperty() {
117 List<Accessor> accessors = AnnotationUtils.analyse(X3.class,
119 assertEquals(1, accessors.size());
120 assertTrue(accessors.get(0) instanceof PropertyAccessor);
121 assertEquals(int.class, accessors.get(0).getType());
123 assertEquals(0, obj.x);
124 accessors.get(0).set(obj, 100);
125 assertEquals(100, obj.x);
129 public void testPrivateProperty() {
130 List<Accessor> accessors = AnnotationUtils.analyse(X4.class,
132 assertEquals(1, accessors.size());
133 assertTrue(accessors.get(0) instanceof PropertyAccessor);
135 assertEquals(0, obj.x);
136 accessors.get(0).set(obj, 100);
137 assertEquals(100, obj.x);
141 public void testMultipleMatches() {
142 List<Accessor> accessors = AnnotationUtils.analyse(X5.class,
144 assertEquals(2, accessors.size());
146 assertEquals(0, obj.x);
147 assertEquals(0, obj.y);
148 for (Accessor accessor : accessors) {
149 accessor.set(obj, 100);
151 assertEquals(100, obj.x);
152 assertEquals(100, obj.y);