Home | History | Annotate | Download | only in internal
      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.spi.Dependency;
     20 
     21 /**
     22  * Resolves a single parameter, to be used in a constructor or method invocation.
     23  */
     24 final class SingleParameterInjector<T> {
     25   private static final Object[] NO_ARGUMENTS = {};
     26 
     27   private final Dependency<T> dependency;
     28   private final BindingImpl<? extends T> binding;
     29 
     30   SingleParameterInjector(Dependency<T> dependency, BindingImpl<? extends T> binding) {
     31     this.dependency = dependency;
     32     this.binding = binding;
     33   }
     34 
     35   private T inject(Errors errors, InternalContext context) throws ErrorsException {
     36     Dependency previous = context.pushDependency(dependency, binding.getSource());
     37     try {
     38       return binding.getInternalFactory().get(errors.withSource(dependency), context, dependency, false);
     39     } finally {
     40       context.popStateAndSetDependency(previous);
     41     }
     42   }
     43 
     44   /**
     45    * Returns an array of parameter values.
     46    */
     47   static Object[] getAll(Errors errors, InternalContext context,
     48       SingleParameterInjector<?>[] parameterInjectors) throws ErrorsException {
     49     if (parameterInjectors == null) {
     50       return NO_ARGUMENTS;
     51     }
     52 
     53     int numErrorsBefore = errors.size();
     54 
     55     int size = parameterInjectors.length;
     56     Object[] parameters = new Object[size];
     57 
     58     // optimization: use manual for/each to save allocating an iterator here
     59     for (int i = 0; i < size; i++) {
     60       SingleParameterInjector<?> parameterInjector = parameterInjectors[i];
     61       try {
     62         parameters[i] = parameterInjector.inject(errors, context);
     63       } catch (ErrorsException e) {
     64         errors.merge(e.getErrors());
     65       }
     66     }
     67 
     68     errors.throwIfNewErrors(numErrorsBefore);
     69     return parameters;
     70   }
     71 }
     72