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.Annotation;
19 import java.lang.reflect.Field;
20 import java.lang.reflect.Method;
21 import java.util.ArrayList;
22 import java.util.List;
25 * Utlities for working with annotations.
27 * @author Erik Brakkee
30 public class AnnotationUtils {
33 * Returns the accessor for a given annotation.
38 * Annotation that must be present.
39 * @return List of accessors. Empty list is returned if no match is found.
41 // TODO move generic analysis part to the reflection package.
42 public static List<Accessor> analyse(Class aClass,
43 Class<? extends Annotation> aAnnotation) {
44 List<Accessor> result = new ArrayList<Accessor>();
46 List<Field> fields = ReflectionUtils.getAllFields(aClass);
47 for (Field field : fields) {
48 if (field.isAnnotationPresent(aAnnotation)) {
49 result.add(new FieldAccessor(field));
52 List<Method> methods = ReflectionUtils.getAllMethods(aClass,
54 for (Method method : methods) {
55 if (method.isAnnotationPresent(aAnnotation)) {
56 String setterName = null;
57 if (method.getName().startsWith("get")) {
58 setterName = method.getName().replaceFirst("get", "set");
59 } else if (method.getName().startsWith("is")) {
60 setterName = method.getName().replaceFirst("is", "set");
63 Class returnType = method.getReturnType();
64 Method setter = method.getDeclaringClass()
65 .getDeclaredMethod(setterName, returnType);
66 result.add(new PropertyAccessor(method, setter));
67 } catch (NoSuchMethodException e) {
68 throw new RuntimeException("Error obtaining setter for " +
69 method.getName() + " in class " + aClass.getName(), e);