blob: 36141056afd9bdc1a85d18f6ebb8e074bc7bb18e [file] [log] [blame]
limpbizkit06898062008-11-02 05:14:55 +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
limpbizkit5ae41eb2009-06-06 17:51:27 +000017package com.google.inject.internal;
limpbizkit06898062008-11-02 05:14:55 +000018
limpbizkit06898062008-11-02 05:14:55 +000019import com.google.inject.spi.Dependency;
20import com.google.inject.spi.InjectionPoint;
21import java.lang.reflect.Field;
22
23/**
24 * Sets an injectable field.
25 */
limpbizkit5ae41eb2009-06-06 17:51:27 +000026final class SingleFieldInjector implements SingleMemberInjector {
limpbizkit06898062008-11-02 05:14:55 +000027 final Field field;
28 final InjectionPoint injectionPoint;
29 final Dependency<?> dependency;
30 final InternalFactory<?> factory;
31
32 public SingleFieldInjector(InjectorImpl injector, InjectionPoint injectionPoint, Errors errors)
33 throws ErrorsException {
34 this.injectionPoint = injectionPoint;
35 this.field = (Field) injectionPoint.getMember();
36 this.dependency = injectionPoint.getDependencies().get(0);
37
38 // Ewwwww...
39 field.setAccessible(true);
40 factory = injector.getInternalFactory(dependency.getKey(), errors);
41 }
42
43 public InjectionPoint getInjectionPoint() {
44 return injectionPoint;
45 }
46
47 public void inject(Errors errors, InternalContext context, Object o) {
48 errors = errors.withSource(dependency);
49
50 context.setDependency(dependency);
51 try {
52 Object value = factory.get(errors, context, dependency);
53 field.set(o, value);
54 } catch (ErrorsException e) {
55 errors.withSource(injectionPoint).merge(e.getErrors());
56 } catch (IllegalAccessException e) {
57 throw new AssertionError(e); // a security manager is blocking us, we're hosed
58 } finally {
59 context.setDependency(null);
60 }
61 }
62}