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.List;
24 * Utlities for working with annotations.
26 * @author Erik Brakkee
29 public class AnnotationUtils {
32 * Returns the accessor for a given annotation.
37 * Annotation that must be present.
38 * @return Accessor to use or null if the annotation is not present.
40 // TODO move generic analysis part to the reflection package.
41 public static Accessor analyse(Class aClass,
42 Class<? extends Annotation> aAnnotation) {
43 List<Field> fields = ReflectionUtils.getAllFields(aClass);
44 for (Field field : fields) {
45 if (field.isAnnotationPresent(aAnnotation)) {
46 return new FieldAccessor(field);
49 List<Method> methods = ReflectionUtils.getAllMethods(aClass,
51 for (Method method : methods) {
52 if (method.isAnnotationPresent(aAnnotation)) {
53 String setterName = null;
54 if (method.getName().startsWith("get")) {
55 setterName = method.getName().replaceFirst("get", "set");
56 } else if (method.getName().startsWith("is")) {
57 setterName = method.getName().replaceFirst("is", "set");
60 Class returnType = method.getReturnType();
61 Method setter = method.getDeclaringClass()
62 .getDeclaredMethod(setterName, returnType);
63 return new PropertyAccessor(method, setter);
64 } catch (NoSuchMethodException e) {
65 throw new RuntimeException("Error obtaining setter for " +
66 method.getName() + " in class " + aClass.getName(), e);