View Javadoc

1   package com.lexicalscope.fluentreflection;
2   
3   import static java.util.Collections.unmodifiableList;
4   
5   import java.lang.reflect.Field;
6   import java.util.ArrayList;
7   import java.util.Collections;
8   import java.util.List;
9   
10  import com.google.inject.TypeLiteral;
11  
12  final class ReflectedFieldsImpl<T> implements ReflectedFields<T> {
13      private final ReflectedTypeFactory reflectedTypeFactory;
14      private final ReflectedSuperclassesAndInterfaces<T> allTypes;
15      private final TypeLiteral<T> typeLiteral;
16  
17      private List<FluentField> declaredFields;
18      private List<FluentField> reflectedFields;
19  
20      ReflectedFieldsImpl(
21              final ReflectedTypeFactory reflectedTypeFactory,
22              final TypeLiteral<T> typeLiteral,
23              final ReflectedSuperclassesAndInterfaces<T> allTypes) {
24          this.reflectedTypeFactory = reflectedTypeFactory;
25          this.typeLiteral = typeLiteral;
26          this.allTypes = allTypes;
27      }
28  
29      @Override public List<FluentField> fields() {
30          if (reflectedFields == null) {
31              final List<FluentField> result = new ArrayList<FluentField>();
32  
33              result.addAll(declaredFields());
34              for (final FluentClass<?> klassToReflect : allTypes.superclassesAndInterfaces()) {
35                  result.addAll(klassToReflect.declaredFields());
36              }
37  
38              Collections.reverse(result);
39              reflectedFields = unmodifiableList(result);
40          }
41          return reflectedFields;
42      }
43  
44      private List<FluentField> getDeclaredFieldsOfClass(final TypeLiteral<?> typeLiteralToReflect) {
45          final List<FluentField> result = new ArrayList<FluentField>();
46          final Field[] declaredFields = typeLiteralToReflect.getRawType().getDeclaredFields();
47          for (final Field method : declaredFields) {
48              result.add(reflectedTypeFactory.field(typeLiteralToReflect, method));
49          }
50          return result;
51      }
52  
53      @Override public List<FluentField> declaredFields() {
54          if (declaredFields == null) {
55              declaredFields = unmodifiableList(getDeclaredFieldsOfClass(typeLiteral));
56          }
57          return declaredFields;
58      }
59  }