aboutsummaryrefslogtreecommitdiff
path: root/extensions/multibindings/src/com/google/inject/multibindings/MultibindingsScanner.java
blob: 95b4d5fa1444c86331ecdc1fff47e1859014af8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/**
 * Copyright (C) 2015 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.inject.multibindings;

import com.google.common.collect.ImmutableSet;
import com.google.inject.AbstractModule;
import com.google.inject.Binder;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
import com.google.inject.spi.InjectionPoint;
import com.google.inject.spi.ModuleAnnotatedMethodScanner;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * Scans a module for annotations that signal multibindings, mapbindings, and optional bindings.
 *
 * @since 4.0
 */
public class MultibindingsScanner {

  private MultibindingsScanner() {}

  /**
   * Returns a module that, when installed, will scan all modules for methods with the annotations
   * {@literal @}{@link ProvidesIntoMap}, {@literal @}{@link ProvidesIntoSet}, and
   * {@literal @}{@link ProvidesIntoOptional}.
   * 
   * <p>This is a convenience method, equivalent to doing
   * {@code binder().scanModulesForAnnotatedMethods(MultibindingsScanner.scanner())}.
   */
  public static Module asModule() {
    return new AbstractModule() {
      @Override protected void configure() {
        binder().scanModulesForAnnotatedMethods(Scanner.INSTANCE);
      }
    };
  }
  
  /**
   * Returns a {@link ModuleAnnotatedMethodScanner} that, when bound, will scan all modules for
   * methods with the annotations {@literal @}{@link ProvidesIntoMap},
   * {@literal @}{@link ProvidesIntoSet}, and {@literal @}{@link ProvidesIntoOptional}.
   */
  public static ModuleAnnotatedMethodScanner scanner() {
    return Scanner.INSTANCE;
  }

  private static class Scanner extends ModuleAnnotatedMethodScanner {
    private static final Scanner INSTANCE = new Scanner();
    
    @Override
    public Set<? extends Class<? extends Annotation>> annotationClasses() {
      return ImmutableSet.of(
          ProvidesIntoSet.class, ProvidesIntoMap.class, ProvidesIntoOptional.class);
    }

    @SuppressWarnings({"unchecked", "rawtypes"}) // mapKey doesn't know its key type
    @Override
    public <T> Key<T> prepareMethod(Binder binder, Annotation annotation, Key<T> key,
        InjectionPoint injectionPoint) {
      Method method = (Method) injectionPoint.getMember();
      AnnotationOrError mapKey = findMapKeyAnnotation(binder, method);
      if (annotation instanceof ProvidesIntoSet) {
        if (mapKey.annotation != null) {
          binder.addError("Found a MapKey annotation on non map binding at %s.", method);
        }
        return Multibinder.newRealSetBinder(binder, key).getKeyForNewItem();
      } else if (annotation instanceof ProvidesIntoMap) {
        if (mapKey.error) {
          // Already failed on the MapKey, don't bother doing more work.
          return key;
        }
        if (mapKey.annotation == null) {
          // If no MapKey, make an error and abort.
          binder.addError("No MapKey found for map binding at %s.", method);
          return key;
        }
        TypeAndValue typeAndValue = typeAndValueOfMapKey(mapKey.annotation);
        return MapBinder.newRealMapBinder(binder, typeAndValue.type, key)
            .getKeyForNewValue(typeAndValue.value);
      } else if (annotation instanceof ProvidesIntoOptional) {
        if (mapKey.annotation != null) {
          binder.addError("Found a MapKey annotation on non map binding at %s.", method);
        }
        switch (((ProvidesIntoOptional)annotation).value()) {
          case DEFAULT:
            return OptionalBinder.newRealOptionalBinder(binder, key).getKeyForDefaultBinding();
          case ACTUAL:
            return OptionalBinder.newRealOptionalBinder(binder, key).getKeyForActualBinding();
        }
      }
      throw new IllegalStateException("Invalid annotation: " + annotation);
    }
  }
  
  private static class AnnotationOrError {
    final Annotation annotation;
    final boolean error;
    AnnotationOrError(Annotation annotation, boolean error) {
      this.annotation = annotation;
      this.error = error;
    }

    static AnnotationOrError forPossiblyNullAnnotation(Annotation annotation) {
      return new AnnotationOrError(annotation, false);
    }
    
    static AnnotationOrError forError() {
      return new AnnotationOrError(null, true);
    }
  }

  private static AnnotationOrError findMapKeyAnnotation(Binder binder, Method method) {
    Annotation foundAnnotation = null;
    for (Annotation annotation : method.getAnnotations()) {
      MapKey mapKey = annotation.annotationType().getAnnotation(MapKey.class);
      if (mapKey != null) {
        if (foundAnnotation != null) {
          binder.addError("Found more than one MapKey annotations on %s.", method);
          return AnnotationOrError.forError();
        }
        if (mapKey.unwrapValue()) {
          try {
            // validate there's a declared method called "value"
            Method valueMethod = annotation.annotationType().getDeclaredMethod("value");
            if (valueMethod.getReturnType().isArray()) {
              binder.addError("Array types are not allowed in a MapKey with unwrapValue=true: %s",                    
                  annotation.annotationType());
              return AnnotationOrError.forError();
            }
          } catch (NoSuchMethodException invalid) {
            binder.addError("No 'value' method in MapKey with unwrapValue=true: %s",
                annotation.annotationType());
            return AnnotationOrError.forError();
          }
        }
        foundAnnotation = annotation;
      }
    }
    return AnnotationOrError.forPossiblyNullAnnotation(foundAnnotation);
  }

  @SuppressWarnings({"unchecked", "rawtypes"})
  static TypeAndValue<?> typeAndValueOfMapKey(Annotation mapKeyAnnotation) {
    if (!mapKeyAnnotation.annotationType().getAnnotation(MapKey.class).unwrapValue()) {
      return new TypeAndValue(TypeLiteral.get(mapKeyAnnotation.annotationType()), mapKeyAnnotation);
    } else {
      try {
        Method valueMethod = mapKeyAnnotation.annotationType().getDeclaredMethod("value");
        valueMethod.setAccessible(true);
        TypeLiteral<?> returnType =
            TypeLiteral.get(mapKeyAnnotation.annotationType()).getReturnType(valueMethod);
        return new TypeAndValue(returnType, valueMethod.invoke(mapKeyAnnotation));
      } catch (NoSuchMethodException e) {
        throw new IllegalStateException(e);
      } catch (SecurityException e) {
        throw new IllegalStateException(e);
      } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
      } catch (InvocationTargetException e) {
        throw new IllegalStateException(e);
      }
    }
  }

  private static class TypeAndValue<T> {
    final TypeLiteral<T> type;
    final T value;

    TypeAndValue(TypeLiteral<T> type, T value) {
      this.type = type;
      this.value = value;
    }
  }
}