View Javadoc

1   package com.atlassian.pageobjects.util;
2   
3   import java.lang.annotation.Annotation;
4   import java.lang.reflect.Field;
5   import java.util.Collection;
6   import java.util.HashMap;
7   import java.util.Map;
8   
9   /**
10   * Utility methods for custom injections
11   */
12  public class InjectUtils
13  {
14      /**
15       * A callback method for fields annotated with a certain annotation
16       * @param <A> The annotation the field is decorated with
17       */
18      public static interface FieldVisitor<A extends Annotation>
19      {
20          void visit(Field field, A annotation);
21      }
22  
23      /**
24       * Executes the callback for each private field marked with the desired annotation
25       *
26       * @param instance The object to inspect
27       * @param annotation The annotation to scan for
28       * @param fieldVisitor The callback when a field is found
29       * @param <A> The annotation type to scan for
30       */
31      public static <A extends Annotation> void forEachFieldWithAnnotation(Object instance, Class<A> annotation, FieldVisitor<A> fieldVisitor)
32      {
33          for (Field field : findAllFields(instance))
34          {
35              A ann = field.getAnnotation(annotation);
36              if (ann != null)
37              {
38                  fieldVisitor.visit(field, ann);
39              }
40          }
41      }
42  
43      private static Collection<Field> findAllFields(Object instance)
44      {
45          Map<String,Field> fields = new HashMap<String,Field>();
46          Class<?> cls = instance.getClass();
47          while (cls != Object.class)
48          {
49              for (Field field : cls.getDeclaredFields())
50              {
51                  if (!fields.containsKey(field.getName()))
52                  {
53                      fields.put(field.getName(), field);
54                  }
55              }
56              cls = cls.getSuperclass();
57          }
58          return fields.values();
59      }
60  }