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; 18 19 import static dagger.internal.codegen.BindingRequest.bindingRequest; 20 import static dagger.internal.codegen.javapoet.CodeBlocks.anonymousProvider; 21 import static dagger.model.RequestKind.INSTANCE; 22 23 import com.squareup.javapoet.ClassName; 24 import com.squareup.javapoet.CodeBlock; 25 import dagger.internal.codegen.FrameworkFieldInitializer.FrameworkInstanceCreationExpression; 26 import dagger.internal.codegen.javapoet.Expression; 27 28 /** 29 * A {@link javax.inject.Provider} creation expression for an anonymous inner class whose 30 * {@code get()} method returns the expression for an instance binding request for its key. 31 */ 32 final class AnonymousProviderCreationExpression 33 implements FrameworkInstanceCreationExpression { 34 private final ContributionBinding binding; 35 private final ComponentBindingExpressions componentBindingExpressions; 36 private final ClassName requestingClass; 37 AnonymousProviderCreationExpression( ContributionBinding binding, ComponentBindingExpressions componentBindingExpressions, ClassName requestingClass)38 AnonymousProviderCreationExpression( 39 ContributionBinding binding, 40 ComponentBindingExpressions componentBindingExpressions, 41 ClassName requestingClass) { 42 this.binding = binding; 43 this.componentBindingExpressions = componentBindingExpressions; 44 this.requestingClass = requestingClass; 45 } 46 47 @Override creationExpression()48 public CodeBlock creationExpression() { 49 BindingRequest instanceExpressionRequest = bindingRequest(binding.key(), INSTANCE); 50 Expression instanceExpression = 51 componentBindingExpressions.getDependencyExpression( 52 instanceExpressionRequest, 53 // Not a real class name, but the actual requestingClass is an inner class within the 54 // given class, not that class itself. 55 requestingClass.nestedClass("Anonymous")); 56 return anonymousProvider(instanceExpression); 57 } 58 } 59