• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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.xprocessing;
18 
19 import static javax.lang.model.element.Modifier.PROTECTED;
20 import static javax.lang.model.element.Modifier.PUBLIC;
21 
22 import androidx.room.compiler.processing.XMethodElement;
23 import androidx.room.compiler.processing.XMethodType;
24 import androidx.room.compiler.processing.XType;
25 import com.squareup.javapoet.MethodSpec;
26 import com.squareup.javapoet.ParameterSpec;
27 import com.squareup.javapoet.TypeName;
28 
29 // TODO(bcorso): Consider moving these methods into XProcessing library.
30 /** A utility class for {@link MethodSpec} helper methods. */
31 public final class MethodSpecs {
32 
33   /** Returns a {@link MethodSpec} that overrides the given method. */
overriding(XMethodElement method, XType owner)34   public static MethodSpec.Builder overriding(XMethodElement method, XType owner) {
35     XMethodType methodType = method.asMemberOf(owner);
36     MethodSpec.Builder builder =
37         // We're overriding the method so we have to use the jvm name here.
38         MethodSpec.methodBuilder(method.getJvmName())
39             .addAnnotation(Override.class)
40             .addTypeVariables(methodType.getTypeVariableNames())
41             .varargs(method.isVarArgs())
42             .returns(methodType.getReturnType().getTypeName());
43     if (method.isPublic()) {
44       builder.addModifiers(PUBLIC);
45     } else if (method.isProtected()) {
46       builder.addModifiers(PROTECTED);
47     }
48     for (int i = 0; i < methodType.getParameterTypes().size(); i++) {
49       String parameterName = method.getParameters().get(i).getJvmName();
50       TypeName parameterType = methodType.getParameterTypes().get(i).getTypeName();
51       builder.addParameter(ParameterSpec.builder(parameterType, parameterName).build());
52     }
53     method.getThrownTypes().stream().map(XType::getTypeName).forEach(builder::addException);
54     return builder;
55   }
56 
MethodSpecs()57   private MethodSpecs() {}
58 }
59