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 public static List<Accessor> analyse(Class aClass,
42 Class<? extends Annotation> aAnnotation) {
43 List<Accessor> result = new ArrayList<Accessor>();
45 List<Field> fields = ReflectionUtils.getAllFields(aClass);
46 for (Field field : fields) {
47 if (field.isAnnotationPresent(aAnnotation)) {
48 result.add(new FieldAccessor(field));
51 List<Method> methods = ReflectionUtils.getAllMethods(aClass,
53 for (Method method : methods) {
54 if (method.isAnnotationPresent(aAnnotation)) {
55 String setterName = null;
56 if (method.getName().startsWith("get")) {
57 setterName = method.getName().replaceFirst("get", "set");
58 } else if (method.getName().startsWith("is")) {
59 setterName = method.getName().replaceFirst("is", "set");
62 Class returnType = method.getReturnType();
63 Method setter = method.getDeclaringClass()
64 .getDeclaredMethod(setterName, returnType);
65 result.add(new PropertyAccessor(method, setter));
66 } catch (NoSuchMethodException e) {
67 throw new RuntimeException("Error obtaining setter for " +
68 method.getName() + " in class " + aClass.getName(), e);