forked from square/dagger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectGraph.java
More file actions
357 lines (321 loc) · 13.7 KB
/
Copy pathObjectGraph.java
File metadata and controls
357 lines (321 loc) · 13.7 KB
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/*
* Copyright (C) 2012 Square, Inc.
* Copyright (C) 2012 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 dagger;
import dagger.internal.Binding;
import dagger.internal.BindingsGroup;
import dagger.internal.FailoverLoader;
import dagger.internal.Keys;
import dagger.internal.Linker;
import dagger.internal.Loader;
import dagger.internal.ModuleAdapter;
import dagger.internal.Modules;
import dagger.internal.ProblemDetector;
import dagger.internal.SetBinding;
import dagger.internal.StaticInjection;
import dagger.internal.ThrowingErrorHandler;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* A graph of objects linked by their dependencies.
*
* <p>The following injection features are supported:
* <ul>
* <li>Field injection. A class may have any number of field injections, and
* fields may be of any visibility. Static fields will be injected each
* time an instance is injected.
* <li>Constructor injection. A class may have a single
* {@code @Inject}-annotated constructor. Classes that have fields
* injected may omit the {@code @Inject} annotation if they have a public
* no-arguments constructor.
* <li>Injection of {@code @Provides} method parameters.
* <li>{@code @Provides} methods annotated {@code @Singleton}.
* <li>Constructor-injected classes annotated {@code @Singleton}.
* <li>Injection of {@code Provider}s.
* <li>Injection of {@code MembersInjector}s.
* <li>Qualifier annotations on injected parameters and fields.
* <li>JSR 330 annotations.
* </ul>
*
* <p>The following injection features are not currently supported:
* <ul>
* <li>Method injection.</li>
* <li>Circular dependencies.</li>
* </ul>
*/
public abstract class ObjectGraph {
ObjectGraph() {
}
/**
* Returns an instance of {@code type}.
*
* @throws IllegalArgumentException if {@code type} is not one of this object
* graph's {@link Module#injects injectable types}.
*/
public abstract <T> T get(Class<T> type);
/**
* Injects the members of {@code instance}, including injectable members
* inherited from its supertypes.
*
* @throws IllegalArgumentException if the runtime type of {@code instance} is
* not one of this object graph's {@link Module#injects injectable types}.
*/
public abstract <T> T inject(T instance);
/**
* Returns a new object graph that includes all of the objects in this graph,
* plus additional objects in the {@literal @}{@link Module}-annotated
* modules. This graph is a subgraph of the returned graph.
*
* <p>The current graph is not modified by this operation: its objects and the
* dependency links between them are unchanged. But this graph's objects may
* be shared by both graphs. For example, the singletons of this graph may be
* injected and used by the returned graph.
*
* <p>This <strong>does not</strong> inject any members or validate the graph.
* See {@link #create} for guidance on injection and validation.
*/
public abstract ObjectGraph plus(Object... modules);
/**
* Do runtime graph problem detection. For fastest graph creation, rely on
* build time tools for graph validation.
*
* @throws IllegalStateException if this graph has problems.
*/
public abstract void validate();
/**
* Injects the static fields of the classes listed in the object graph's
* {@code staticInjections} property.
*/
public abstract void injectStatics();
/**
* Returns a new dependency graph using the {@literal @}{@link
* Module}-annotated modules.
*
* <p>This <strong>does not</strong> inject any members. Most applications
* should call {@link #injectStatics} to inject static members and {@link
* #inject} or get {@link #get(Class)} to inject instance members when this
* method has returned.
*
* <p>This <strong>does not</strong> validate the graph. Rely on build time
* tools for graph validation, or call {@link #validate} to find problems in
* the graph at runtime.
*/
public static ObjectGraph create(Object... modules) {
return DaggerObjectGraph.makeGraph(null, new FailoverLoader(), modules);
}
// visible for testing
static ObjectGraph createWith(Loader loader, Object... modules) {
return DaggerObjectGraph.makeGraph(null, loader, modules);
}
// TODO(cgruber): Move this internal implementation of ObjectGraph into the internal package.
static class DaggerObjectGraph extends ObjectGraph {
private final DaggerObjectGraph base;
private final Linker linker;
private final Loader plugin;
private final Map<Class<?>, StaticInjection> staticInjections;
private final Map<String, Class<?>> injectableTypes;
private final List<SetBinding<?>> setBindings;
DaggerObjectGraph(DaggerObjectGraph base,
Linker linker,
Loader plugin,
Map<Class<?>, StaticInjection> staticInjections,
Map<String, Class<?>> injectableTypes,
List<SetBinding<?>> setBindings) {
this.base = base;
this.linker = checkNotNull(linker, "linker");
this.plugin = checkNotNull(plugin, "plugin");
this.staticInjections = checkNotNull(staticInjections, "staticInjections");
this.injectableTypes = checkNotNull(injectableTypes, "injectableTypes");
this.setBindings = checkNotNull(setBindings, "setBindings");
}
private static <T> T checkNotNull(T object, String label) {
if (object == null) throw new NullPointerException(label);
return object;
}
static ObjectGraph makeGraph(DaggerObjectGraph base, Loader plugin, Object... modules) {
Map<String, Class<?>> injectableTypes = new LinkedHashMap<String, Class<?>>();
Map<Class<?>, StaticInjection> staticInjections
= new LinkedHashMap<Class<?>, StaticInjection>();
StandardBindings baseBindings =
(base == null) ? new StandardBindings() : new StandardBindings(base.setBindings);
BindingsGroup overrideBindings = new OverridesBindings();
Map<ModuleAdapter<?>, Object> loadedModules = Modules.loadModules(plugin, modules);
for (Entry<ModuleAdapter<?>, Object> loadedModule : loadedModules.entrySet()) {
ModuleAdapter<Object> moduleAdapter = (ModuleAdapter<Object>) loadedModule.getKey();
for (int i = 0; i < moduleAdapter.injectableTypes.length; i++) {
injectableTypes.put(moduleAdapter.injectableTypes[i], moduleAdapter.moduleClass);
}
for (int i = 0; i < moduleAdapter.staticInjections.length; i++) {
staticInjections.put(moduleAdapter.staticInjections[i], null);
}
try {
BindingsGroup addTo = moduleAdapter.overrides ? overrideBindings : baseBindings;
moduleAdapter.getBindings(addTo, loadedModule.getValue());
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
moduleAdapter.moduleClass.getSimpleName() + ": " + e.getMessage(), e);
}
}
// Create a linker and install all of the user's bindings
Linker linker =
new Linker((base != null) ? base.linker : null, plugin, new ThrowingErrorHandler());
linker.installBindings(baseBindings);
linker.installBindings(overrideBindings);
return new DaggerObjectGraph(
base, linker, plugin, staticInjections, injectableTypes, baseBindings.setBindings);
}
@Override public ObjectGraph plus(Object... modules) {
linkEverything();
return makeGraph(this, plugin, modules);
}
private void linkStaticInjections() {
for (Map.Entry<Class<?>, StaticInjection> entry : staticInjections.entrySet()) {
StaticInjection staticInjection = entry.getValue();
if (staticInjection == null) {
staticInjection = plugin.getStaticInjection(entry.getKey());
entry.setValue(staticInjection);
}
staticInjection.attach(linker);
}
}
private void linkInjectableTypes() {
for (Map.Entry<String, Class<?>> entry : injectableTypes.entrySet()) {
linker.requestBinding(entry.getKey(), entry.getValue(), entry.getValue().getClassLoader(),
false, true);
}
}
@Override public void validate() {
Map<String, Binding<?>> allBindings = linkEverything();
new ProblemDetector().detectProblems(allBindings.values());
}
/**
* Links all bindings, injectable types and static injections.
*/
private Map<String, Binding<?>> linkEverything() {
Map<String, Binding<?>> bindings = linker.fullyLinkedBindings();
if (bindings != null) {
return bindings;
}
synchronized (linker) {
if ((bindings = linker.fullyLinkedBindings()) != null) {
return bindings;
}
linkStaticInjections();
linkInjectableTypes();
return linker.linkAll(); // Linker.linkAll() implicitly does Linker.linkRequested().
}
}
@Override public void injectStatics() {
// We call linkStaticInjections() twice on purpose. The first time through
// we request all of the bindings we need. The linker returns null for
// bindings it doesn't have. Then we ask the linker to link all of those
// requested bindings. Finally we call linkStaticInjections() again: this
// time the linker won't return null because everything has been linked.
synchronized (linker) {
linkStaticInjections();
linker.linkRequested();
linkStaticInjections();
}
for (Map.Entry<Class<?>, StaticInjection> entry : staticInjections.entrySet()) {
entry.getValue().inject();
}
}
@Override public <T> T get(Class<T> type) {
String key = Keys.get(type);
String injectableTypeKey = type.isInterface() ? key : Keys.getMembersKey(type);
ClassLoader classLoader = type.getClassLoader();
@SuppressWarnings("unchecked") // The linker matches keys to bindings by their type.
Binding<T> binding =
(Binding<T>) getInjectableTypeBinding(classLoader, injectableTypeKey, key);
return binding.get();
}
@Override public <T> T inject(T instance) {
String membersKey = Keys.getMembersKey(instance.getClass());
ClassLoader classLoader = instance.getClass().getClassLoader();
@SuppressWarnings("unchecked") // The linker matches keys to bindings by their type.
Binding<T> binding =
(Binding<T>) getInjectableTypeBinding(classLoader, membersKey, membersKey);
binding.injectMembers(instance);
return instance;
}
/**
* @param classLoader the {@code ClassLoader} used to load dependent bindings.
* @param injectableKey the key used to store the injectable type. This
* is a provides key for interfaces and a members injection key for
* other types. That way keys can always be created, even if the type
* has no injectable constructor.
* @param key the key to use when retrieving the binding. This may be a
* regular (provider) key or a members key.
*/
private Binding<?> getInjectableTypeBinding(
ClassLoader classLoader, String injectableKey, String key) {
Class<?> moduleClass = null;
for (DaggerObjectGraph graph = this; graph != null; graph = graph.base) {
moduleClass = graph.injectableTypes.get(injectableKey);
if (moduleClass != null) break;
}
if (moduleClass == null) {
throw new IllegalArgumentException("No inject registered for " + injectableKey
+ ". You must explicitly add it to the 'injects' option in one of your modules.");
}
synchronized (linker) {
Binding<?> binding = linker.requestBinding(key, moduleClass, classLoader, false, true);
if (binding == null || !binding.isLinked()) {
linker.linkRequested();
binding = linker.requestBinding(key, moduleClass, classLoader, false, true);
}
return binding;
}
}
}
/**
* A BindingsGroup which fails when existing values are clobbered and sets aside
* {@link SetBinding}.
*/
private static final class StandardBindings extends BindingsGroup {
private final List<SetBinding<?>> setBindings;
public StandardBindings() {
setBindings = new ArrayList<SetBinding<?>>();
}
public StandardBindings(List<SetBinding<?>> baseSetBindings) {
setBindings = new ArrayList<SetBinding<?>>(baseSetBindings.size());
for (SetBinding<?> sb : baseSetBindings) {
@SuppressWarnings({ "rawtypes", "unchecked" })
SetBinding<?> child = new SetBinding(sb);
setBindings.add(child);
put(child.provideKey, child);
}
}
@Override public Binding<?> contributeSetBinding(String key, SetBinding<?> value) {
setBindings.add(value);
return super.put(key, value);
}
}
/**
* A BindingsGroup which throws an {@link IllegalArgumentException} when a
* {@link SetBinding} is contributed, since overrides modules cannot contribute such
* bindings.
*/
private static final class OverridesBindings extends BindingsGroup {
OverridesBindings() { }
@Override public Binding<?> contributeSetBinding(String key, SetBinding<?> value) {
throw new IllegalArgumentException("Module overrides cannot contribute set bindings.");
}
}
}