1 /* 2 * Copyright (C) 2014 The Dagger Authors. 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 dagger.internal; 18 19 import static dagger.internal.Preconditions.checkNotNull; 20 21 import javax.inject.Provider; 22 23 /** 24 * A DelegateFactory that is used to stitch Provider/Lazy indirection based dependency cycles. 25 * 26 * @since 2.0.1 27 */ 28 public final class DelegateFactory<T> implements Factory<T> { 29 private Provider<T> delegate; 30 31 @Override get()32 public T get() { 33 if (delegate == null) { 34 throw new IllegalStateException(); 35 } 36 return delegate.get(); 37 } 38 39 // TODO(ronshapiro): remove this once we can reasonably expect generated code is no longer using 40 // this method 41 @Deprecated setDelegatedProvider(Provider<T> delegate)42 public void setDelegatedProvider(Provider<T> delegate) { 43 setDelegate(this, delegate); 44 } 45 46 /** 47 * Sets {@code delegateFactory}'s delegate provider to {@code delegate}. 48 * 49 * <p>{@code delegateFactory} must be an instance of {@link DelegateFactory}, otherwise this 50 * method will throw a {@link ClassCastException}. 51 */ setDelegate(Provider<T> delegateFactory, Provider<T> delegate)52 public static <T> void setDelegate(Provider<T> delegateFactory, Provider<T> delegate) { 53 checkNotNull(delegate); 54 DelegateFactory<T> asDelegateFactory = (DelegateFactory<T>) delegateFactory; 55 if (asDelegateFactory.delegate != null) { 56 throw new IllegalStateException(); 57 } 58 asDelegateFactory.delegate = delegate; 59 } 60 61 /** 62 * Returns the factory's delegate. 63 * 64 * @throws NullPointerException if the delegate has not been set 65 */ getDelegate()66 Provider<T> getDelegate() { 67 return checkNotNull(delegate); 68 } 69 } 70 71