blob: 401cb6a64b74cb38d761e8b71fb446ad3b282946 [file] [log] [blame]
limpbizkit3d58d6b2008-03-08 16:11:47 +00001/**
2 * Copyright (C) 2008 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.inject;
18
19import com.google.inject.commands.RequestStaticInjectionCommand;
20
21import java.util.ArrayList;
22import java.util.List;
23
24/**
25 * Handles {@link Binder#requestStaticInjection} commands.
26 *
27 * @author crazybob@google.com (Bob Lee)
28 * @author jessewilson@google.com (Jesse Wilson)
29 */
30class RequestStaticInjectionCommandProcessor extends CommandProcessor {
31
32 private final List<StaticInjection> staticInjections
33 = new ArrayList<StaticInjection>();
34
35 @Override public Boolean visitRequestStaticInjection(RequestStaticInjectionCommand command) {
36 for (Class<?> type : command.getTypes()) {
37 staticInjections.add(new StaticInjection(command.getSource(), type));
38 }
39 return true;
40 }
41
42 public void validate(InjectorImpl injector) {
43 for (StaticInjection staticInjection : staticInjections) {
44 staticInjection.validate(injector);
45 }
46 }
47
48 public void injectMembers(InjectorImpl injector) {
49 for (StaticInjection staticInjection : staticInjections) {
50 staticInjection.injectMembers(injector);
51 }
52 }
53
54 /**
55 * A requested static injection.
56 */
57 private class StaticInjection {
58 final Object source;
59 final Class<?> type;
60 final List<InjectorImpl.SingleMemberInjector> memberInjectors
61 = new ArrayList<InjectorImpl.SingleMemberInjector>();
62
63 public StaticInjection(Object source, Class type) {
64 this.source = source;
65 this.type = type;
66 }
67
68 void validate(final InjectorImpl injector) {
69 injector.withDefaultSource(source,
70 new Runnable() {
71 public void run() {
72 injector.addSingleInjectorsForFields(
73 type.getDeclaredFields(), true, memberInjectors);
74 injector.addSingleInjectorsForMethods(
75 type.getDeclaredMethods(), true, memberInjectors);
76 }
77 });
78 }
79
80 void injectMembers(InjectorImpl injector) {
81 injector.callInContext(new ContextualCallable<Void>() {
82 public Void call(InternalContext context) {
83 for (InjectorImpl.SingleMemberInjector injector : memberInjectors) {
84 injector.inject(context, null);
85 }
86 return null;
87 }
88 });
89 }
90 }
91}