limpbizkit | 0689806 | 2008-11-02 05:14:55 +0000 | [diff] [blame] | 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 | |
limpbizkit | 5ae41eb | 2009-06-06 17:51:27 +0000 | [diff] [blame^] | 17 | package com.google.inject.internal; |
limpbizkit | 0689806 | 2008-11-02 05:14:55 +0000 | [diff] [blame] | 18 | |
limpbizkit | 0689806 | 2008-11-02 05:14:55 +0000 | [diff] [blame] | 19 | import com.google.inject.spi.Dependency; |
| 20 | import com.google.inject.spi.InjectionPoint; |
| 21 | import java.lang.reflect.Field; |
| 22 | |
| 23 | /** |
| 24 | * Sets an injectable field. |
| 25 | */ |
limpbizkit | 5ae41eb | 2009-06-06 17:51:27 +0000 | [diff] [blame^] | 26 | final class SingleFieldInjector implements SingleMemberInjector { |
limpbizkit | 0689806 | 2008-11-02 05:14:55 +0000 | [diff] [blame] | 27 | 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 | } |