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