1/**
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.internal;
18
19import com.google.inject.internal.InjectorImpl.JitLimitation;
20import com.google.inject.spi.Dependency;
21import com.google.inject.spi.InjectionPoint;
22
23import java.lang.reflect.Field;
24
25/**
26 * Sets an injectable field.
27 */
28final class SingleFieldInjector implements SingleMemberInjector {
29  final Field field;
30  final InjectionPoint injectionPoint;
31  final Dependency<?> dependency;
32  final BindingImpl<?> binding;
33
34  public SingleFieldInjector(InjectorImpl injector, InjectionPoint injectionPoint, Errors errors)
35      throws ErrorsException {
36    this.injectionPoint = injectionPoint;
37    this.field = (Field) injectionPoint.getMember();
38    this.dependency = injectionPoint.getDependencies().get(0);
39
40    // Ewwwww...
41    field.setAccessible(true);
42    binding = injector.getBindingOrThrow(dependency.getKey(), errors, JitLimitation.NO_JIT);
43  }
44
45  public InjectionPoint getInjectionPoint() {
46    return injectionPoint;
47  }
48
49  public void inject(Errors errors, InternalContext context, Object o) {
50    errors = errors.withSource(dependency);
51
52    Dependency previous = context.pushDependency(dependency, binding.getSource());
53    try {
54      Object value = binding.getInternalFactory().get(errors, context, dependency, false);
55      field.set(o, value);
56    } catch (ErrorsException e) {
57      errors.withSource(injectionPoint).merge(e.getErrors());
58    } catch (IllegalAccessException e) {
59      throw new AssertionError(e); // a security manager is blocking us, we're hosed
60    } finally {
61      context.popStateAndSetDependency(previous);
62    }
63  }
64}
65