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