1 /* 2 * Copyright (C) 2015 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.codegen.writing; 18 19 import static com.google.common.base.Preconditions.checkNotNull; 20 import static dagger.internal.codegen.binding.SourceFiles.generatedClassNameForBinding; 21 import static dagger.model.BindingKind.INJECTION; 22 23 import com.squareup.javapoet.CodeBlock; 24 import dagger.internal.codegen.binding.ContributionBinding; 25 import dagger.internal.codegen.javapoet.CodeBlocks; 26 import dagger.internal.codegen.writing.FrameworkFieldInitializer.FrameworkInstanceCreationExpression; 27 import javax.inject.Provider; 28 29 /** 30 * A {@link Provider} creation expression for an {@link javax.inject.Inject @Inject}-constructed 31 * class or a {@link dagger.Provides @Provides}-annotated module method. 32 */ 33 // TODO(dpb): Resolve with ProducerCreationExpression. 34 final class InjectionOrProvisionProviderCreationExpression 35 implements FrameworkInstanceCreationExpression { 36 37 private final ContributionBinding binding; 38 private final ComponentBindingExpressions componentBindingExpressions; 39 InjectionOrProvisionProviderCreationExpression( ContributionBinding binding, ComponentBindingExpressions componentBindingExpressions)40 InjectionOrProvisionProviderCreationExpression( 41 ContributionBinding binding, ComponentBindingExpressions componentBindingExpressions) { 42 this.binding = checkNotNull(binding); 43 this.componentBindingExpressions = checkNotNull(componentBindingExpressions); 44 } 45 46 @Override creationExpression()47 public CodeBlock creationExpression() { 48 CodeBlock createFactory = 49 CodeBlock.of( 50 "$T.create($L)", 51 generatedClassNameForBinding(binding), 52 componentBindingExpressions.getCreateMethodArgumentsCodeBlock(binding)); 53 54 // When scoping a parameterized factory for an @Inject class, Java 7 cannot always infer the 55 // type properly, so cast to a raw framework type before scoping. 56 if (binding.kind().equals(INJECTION) 57 && binding.unresolved().isPresent() 58 && binding.scope().isPresent()) { 59 return CodeBlocks.cast(createFactory, Provider.class); 60 } else { 61 return createFactory; 62 } 63 } 64 } 65