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.common.base.Objects;
     20 import com.google.inject.Key;
     21 import com.google.inject.internal.InjectorImpl.JitLimitation;
     22 import com.google.inject.spi.Dependency;
     23 
     24 /**
     25  * A placeholder which enables us to swap in the real factory once the injector is created.
     26  * Used for a linked binding, so that getting the linked binding returns the link's factory.
     27  */
     28 final class FactoryProxy<T> implements InternalFactory<T>, CreationListener {
     29 
     30   private final InjectorImpl injector;
     31   private final Key<T> key;
     32   private final Key<? extends T> targetKey;
     33   private final Object source;
     34 
     35   private InternalFactory<? extends T> targetFactory;
     36 
     37   FactoryProxy(InjectorImpl injector, Key<T> key, Key<? extends T> targetKey, Object source) {
     38     this.injector = injector;
     39     this.key = key;
     40     this.targetKey = targetKey;
     41     this.source = source;
     42   }
     43 
     44   public void notify(final Errors errors) {
     45     try {
     46       targetFactory = injector.getInternalFactory(targetKey, errors.withSource(source), JitLimitation.NEW_OR_EXISTING_JIT);
     47     } catch (ErrorsException e) {
     48       errors.merge(e.getErrors());
     49     }
     50   }
     51 
     52   public T get(Errors errors, InternalContext context, Dependency<?> dependency, boolean linked)
     53       throws ErrorsException {
     54     context.pushState(targetKey, source);
     55     try {
     56       return targetFactory.get(errors.withSource(targetKey), context, dependency, true);
     57     } finally {
     58       context.popState();
     59     }
     60   }
     61 
     62   @Override public String toString() {
     63     return Objects.toStringHelper(FactoryProxy.class)
     64         .add("key", key)
     65         .add("provider", targetFactory)
     66         .toString();
     67   }
     68 }
     69