X-Git-Url: http://wamblee.org/gitweb/?a=blobdiff_plain;f=support%2Fgeneral%2Fsrc%2Fmain%2Fjava%2Forg%2Fwamblee%2Freflection%2FAnnotationUtils.java;h=5ea776b3217dac607e939adcfcc49025c2eeb8df;hb=8de6b7f0ebece61ee45ae70c2faa1898c7b60da7;hp=5c701fb5ae57878a7dfec4659413ea9a185cf9b8;hpb=7c1f4aa47fcc3098427073b5ce9f6abed8befa7c;p=utils diff --git a/support/general/src/main/java/org/wamblee/reflection/AnnotationUtils.java b/support/general/src/main/java/org/wamblee/reflection/AnnotationUtils.java index 5c701fb5..5ea776b3 100644 --- a/support/general/src/main/java/org/wamblee/reflection/AnnotationUtils.java +++ b/support/general/src/main/java/org/wamblee/reflection/AnnotationUtils.java @@ -15,6 +15,12 @@ */ package org.wamblee.reflection; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + /** * Utlities for working with annotations. * @@ -23,4 +29,48 @@ 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 List of accessors. Empty list is returned if no match is found. + */ + // TODO move generic analysis part to the reflection package. + public static List analyse(Class aClass, + Class aAnnotation) { + List result = new ArrayList(); + + List fields = ReflectionUtils.getAllFields(aClass); + for (Field field : fields) { + if (field.isAnnotationPresent(aAnnotation)) { + result.add(new FieldAccessor(field)); + } + } + List 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); + result.add(new PropertyAccessor(method, setter)); + } catch (NoSuchMethodException e) { + throw new RuntimeException("Error obtaining setter for " + + method.getName() + " in class " + aClass.getName(), e); + } + } + } + return result; + } + }