| 1 package org.objectweb.celtix.common.annotation; 2 3 import java.lang.annotation.Annotation ; 4 import java.lang.reflect.AnnotatedElement ; 5 import java.lang.reflect.Field ; 6 import java.lang.reflect.InvocationTargetException ; 7 import java.lang.reflect.Method ; 8 import java.util.List ; 9 import java.util.logging.Level ; 10 import java.util.logging.Logger ; 11 12 import org.objectweb.celtix.common.i18n.Message; 13 import org.objectweb.celtix.common.logging.LogUtils; 14 15 16 22 public class AnnotationProcessor { 23 24 private static final Logger LOG = LogUtils.getL7dLogger(AnnotationProcessor.class); 25 26 private static Method visitClassMethod; 27 private static Method visitFieldMethod; 28 private static Method visitMethodMethod; 29 30 static { 31 try { 32 visitClassMethod = AnnotationVisitor.class.getMethod("visitClass", Class .class, Annotation .class); 33 visitFieldMethod = AnnotationVisitor.class.getMethod("visitField", Field .class, Annotation .class); 34 visitMethodMethod = AnnotationVisitor.class.getMethod("visitMethod", 35 Method .class, Annotation .class); 36 37 } catch (NoSuchMethodException e) { 38 } 40 41 } 42 43 private final Object target; 44 private List <Class <? extends Annotation >> annotationTypes; 45 46 47 public AnnotationProcessor(Object o) { 48 if (o == null) { 49 throw new IllegalArgumentException (new Message("INVALID_CTOR_ARGS", LOG).toString()); 50 } 51 target = o; 52 } 53 54 60 public void accept(AnnotationVisitor visitor) { 61 62 if (visitor == null) { 63 throw new IllegalArgumentException (); 64 } 65 66 annotationTypes = visitor.getTargetAnnotations(); 67 visitor.setTarget(target); 68 processClass(visitor); 69 processFields(visitor); 70 processMethods(visitor); 71 } 72 73 74 private void processMethods(AnnotationVisitor visitor) { 75 76 visitAnnotatedElement(target.getClass().getDeclaredMethods(), visitor, visitMethodMethod); 77 } 78 79 private void processFields(AnnotationVisitor visitor) { 80 81 visitAnnotatedElement(target.getClass().getDeclaredFields(), visitor, visitFieldMethod); 82 } 83 84 85 private void processClass(AnnotationVisitor visitor) { 86 Class <?>[] classes = {target.getClass()}; 87 visitAnnotatedElement(classes, visitor, visitClassMethod); 88 } 89 90 private <U extends AnnotatedElement > void visitAnnotatedElement(U[] elements, 91 AnnotationVisitor visitor, 92 Method visitorMethod) { 93 94 for (U element : elements) { 95 for (Class <? extends Annotation > clz : annotationTypes) { 96 Annotation ann = element.getAnnotation(clz); 97 if (ann != null) { 98 try { 99 visitorMethod.invoke(visitor, element, ann); 100 } catch (IllegalAccessException e) { 101 } catch (InvocationTargetException e) { 103 Throwable cause = e.getCause() == null ? e : e.getCause(); 104 LogUtils.log(LOG, Level.SEVERE, "VISITOR_RAISED_EXCEPTION", cause, visitor); 105 } 106 } 107 } 108 } 109 } 110 } 111 | Popular Tags |