(no commit message)
[utils] / support / general / src / main / java / org / wamblee / reflection / AnnotationUtils.java
index 5c701fb5ae57878a7dfec4659413ea9a185cf9b8..d31163fb11812487096953b9662d716f7dca5d1b 100644 (file)
  */
 package org.wamblee.reflection;
 
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.List;
+
 /**
  * Utlities for working with annotations. 
  * 
@@ -23,4 +28,46 @@ package org.wamblee.reflection;
  */
 public class AnnotationUtils {
 
+    /**
+     * Returns the accessor for a given annotation.
+     * 
+     * @param aClass
+     *            Class to analyse.
+     * @param aAnnotation
+     *            Annotation that must be present.
+     * @return Accessor to use or null if the annotation is not present.
+     */
+    // TODO move generic analysis part to the reflection package.
+    public static Accessor analyse(Class aClass,
+        Class<? extends Annotation> aAnnotation) {
+        List<Field> fields = ReflectionUtils.getAllFields(aClass);
+        for (Field field : fields) {
+            if (field.isAnnotationPresent(aAnnotation)) {
+                return new FieldAccessor(field);
+            }
+        }
+        List<Method> methods = ReflectionUtils.getAllMethods(aClass,
+            Object.class);
+        for (Method method : methods) {
+            if (method.isAnnotationPresent(aAnnotation)) {
+                String setterName = null;
+                if (method.getName().startsWith("get")) {
+                    setterName = method.getName().replaceFirst("get", "set");
+                } else if (method.getName().startsWith("is")) {
+                    setterName = method.getName().replaceFirst("is", "set");
+                }
+                try {
+                    Class returnType = method.getReturnType();
+                    Method setter = method.getDeclaringClass()
+                        .getDeclaredMethod(setterName, returnType);
+                    return new PropertyAccessor(method, setter);
+                } catch (NoSuchMethodException e) {
+                    throw new RuntimeException("Error obtaining setter for " +
+                        method.getName() + " in class " + aClass.getName(), e);
+                }
+            }
+        }
+        return null;
+    }
+
 }