Java Code Examples for com.squareup.javapoet.TypeVariableName#get()

The following examples show how to use com.squareup.javapoet.TypeVariableName#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PsiTypeVariablesExtractor.java    From litho with Apache License 2.0 6 votes vote down vote up
public static ImmutableList<TypeVariableName> getTypeVariables(PsiClass psiClass) {
  PsiTypeParameter[] psiTypeParameters = psiClass.getTypeParameters();

  final List<TypeVariableName> typeVariables = new ArrayList<>(psiTypeParameters.length);
  for (PsiTypeParameter psiTypeParameter : psiTypeParameters) {
    final PsiReferenceList extendsList = psiTypeParameter.getExtendsList();
    final PsiClassType[] psiClassTypes = extendsList.getReferencedTypes();

    final TypeName[] boundsTypeNames = new TypeName[psiClassTypes.length];
    for (int i = 0, size = psiClassTypes.length; i < size; i++) {
      boundsTypeNames[i] = PsiTypeUtils.getTypeName(psiClassTypes[i]);
    }

    final TypeVariableName typeVariable =
        TypeVariableName.get(psiTypeParameter.getName(), boundsTypeNames);
    typeVariables.add(typeVariable);
  }

  return ImmutableList.copyOf(typeVariables);
}
 
Example 2
Source File: MethodParamModelUtilsTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTypeVariablesOnParameterizedTypeRecursive() {
  TypeVariableName type1 = TypeVariableName.get("R");
  TypeVariableName type2 = TypeVariableName.get("S");
  TypeVariableName type3 = TypeVariableName.get("T");

  TypeName type =
      ParameterizedTypeName.get(
          ClassName.bestGuess("java.lang.Object"),
          type1,
          type2,
          ParameterizedTypeName.get(ClassName.bestGuess("java.lang.Object"), type3));
  assertThat(MethodParamModelUtils.getTypeVariables(type)).hasSize(3);
  assertThat(MethodParamModelUtils.getTypeVariables(type)).contains(type1);
  assertThat(MethodParamModelUtils.getTypeVariables(type)).contains(type2);
  assertThat(MethodParamModelUtils.getTypeVariables(type)).contains(type3);
}
 
Example 3
Source File: TypeVariablesExtractor.java    From litho with Apache License 2.0 6 votes vote down vote up
/** Get the type variables from the given {@link TypeElement}. */
public static List<TypeVariableName> getTypeVariables(TypeElement typeElement) {
  final List<? extends TypeParameterElement> typeParameters = typeElement.getTypeParameters();
  final int typeParameterCount = typeParameters.size();

  final List<TypeVariableName> typeVariables = new ArrayList<>(typeParameterCount);
  for (TypeParameterElement typeParameterElement : typeParameters) {
    final int boundTypesCount = typeParameterElement.getBounds().size();

    final TypeName[] boundsTypeNames = new TypeName[boundTypesCount];
    for (int i = 0; i < boundTypesCount; i++) {
      boundsTypeNames[i] = TypeName.get(typeParameterElement.getBounds().get(i));
    }

    final TypeVariableName typeVariable =
        TypeVariableName.get(typeParameterElement.getSimpleName().toString(), boundsTypeNames);
    typeVariables.add(typeVariable);
  }

  return typeVariables;
}
 
Example 4
Source File: CopyReplacer.java    From data-mediator with Apache License 2.0 6 votes vote down vote up
@Override
public TypeName replaceReturnType(String currentPkg, String directParentInterface, String curClassname,
                                  List<? extends TypeMirror> superInterfaces, TypeName superClass, ExecutableElement method) {
    final TypeMirror returnType = method.getReturnType();
    switch (method.getSimpleName().toString()){
        case TypeCopyableFiller.NAME_COPY: {
            switch (returnType.getKind()) {
                case TYPEVAR: //泛型
                    return  TypeVariableName.get(directParentInterface);

                default:
                    return TypeName.get(returnType);
            }
        }

        default:
            return TypeName.get(returnType);

    }

}
 
Example 5
Source File: ProtocolSpec.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
default TypeName executeFutureValueType(OperationModel opModel, PoetExtensions poetExtensions) {
    if (opModel.hasEventStreamOutput()) {
        return ClassName.get(Void.class);
    } else if (opModel.hasStreamingOutput()) {
        return TypeVariableName.get("ReturnT");
    } else {
        return getPojoResponseType(opModel, poetExtensions);
    }
}
 
Example 6
Source File: SmartEventProcessor.java    From SmartEventBus with Apache License 2.0 5 votes vote down vote up
private TypeName getTypeName(String name) {
    if (name == null || name.length() == 0) {
        return null;
    }
    java.lang.reflect.Type type = getType(name);
    if (type != null) {
        return ClassName.get(type);
    } else {
        return TypeVariableName.get(name);
    }
}
 
Example 7
Source File: ClientClassUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
static MethodSpec applySignerOverrideMethod(PoetExtensions poetExtensions, IntermediateModel model) {
    String signerOverrideVariable = "signerOverride";

    TypeVariableName typeVariableName =
        TypeVariableName.get("T", poetExtensions.getModelClass(model.getSdkRequestBaseClassName()));

    ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName
        .get(ClassName.get(Consumer.class), ClassName.get(AwsRequestOverrideConfiguration.Builder.class));

    CodeBlock codeBlock = CodeBlock.builder()
                                   .beginControlFlow("if (request.overrideConfiguration().flatMap(c -> c.signer())"
                                                     + ".isPresent())")
                                   .addStatement("return request")
                                   .endControlFlow()
                                   .addStatement("$T $L = b -> b.signer(signer).build()",
                                                 parameterizedTypeName,
                                                 signerOverrideVariable)
                                   .addStatement("$1T overrideConfiguration =\n"
                                                 + "            request.overrideConfiguration().map(c -> c.toBuilder()"
                                                 + ".applyMutation($2L).build())\n"
                                                 + "            .orElse((AwsRequestOverrideConfiguration.builder()"
                                                 + ".applyMutation($2L).build()))",
                                                 AwsRequestOverrideConfiguration.class,
                                                 signerOverrideVariable)
                                   .addStatement("return (T) request.toBuilder().overrideConfiguration"
                                                 + "(overrideConfiguration).build()")
                                   .build();

    return MethodSpec.methodBuilder("applySignerOverride")
                     .addModifiers(Modifier.PRIVATE)
                     .addParameter(typeVariableName, "request")
                     .addParameter(Signer.class, "signer")
                     .addTypeVariable(typeVariableName)
                     .addCode(codeBlock)
                     .returns(typeVariableName)
                     .build();
}
 
Example 8
Source File: ClientClassUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
static MethodSpec applyPaginatorUserAgentMethod(PoetExtensions poetExtensions, IntermediateModel model) {

        TypeVariableName typeVariableName =
            TypeVariableName.get("T", poetExtensions.getModelClass(model.getSdkRequestBaseClassName()));

        ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName
            .get(ClassName.get(Consumer.class), ClassName.get(AwsRequestOverrideConfiguration.Builder.class));

        CodeBlock codeBlock = CodeBlock.builder()
                                       .addStatement("$T userAgentApplier = b -> b.addApiName($T.builder().version"
                                                     + "($T.SDK_VERSION).name($S).build())",
                                                     parameterizedTypeName, ApiName.class,
                                                     VersionInfo.class,
                                                     PAGINATOR_USER_AGENT)
                                       .addStatement("$T overrideConfiguration =\n"
                                                     + "            request.overrideConfiguration().map(c -> c.toBuilder()"
                                                     + ".applyMutation"
                                                     + "(userAgentApplier).build())\n"
                                                     + "            .orElse((AwsRequestOverrideConfiguration.builder()"
                                                     + ".applyMutation"
                                                     + "(userAgentApplier).build()))", AwsRequestOverrideConfiguration.class)
                                       .addStatement("return (T) request.toBuilder().overrideConfiguration"
                                                     + "(overrideConfiguration).build()")
                                       .build();

        return MethodSpec.methodBuilder("applyPaginatorUserAgent")
                         .addModifiers(Modifier.PRIVATE)
                         .addParameter(typeVariableName, "request")
                         .addTypeVariable(typeVariableName)
                         .addCode(codeBlock)
                         .returns(typeVariableName)
                         .build();
    }
 
Example 9
Source File: PsiMethodExtractorUtils.java    From litho with Apache License 2.0 5 votes vote down vote up
private static TypeVariableName toTypeVariableName(PsiTypeParameter psiTypeParameter) {
  String typeName = psiTypeParameter.getName();
  TypeName[] typeBounds =
      Arrays.stream(psiTypeParameter.getBounds())
          .filter(PsiType.class::isInstance)
          .map(bound -> PsiTypeUtils.getTypeName((PsiType) bound))
          .toArray(TypeName[]::new);
  return TypeVariableName.get(typeName, typeBounds);
}
 
Example 10
Source File: JsonProtocolSpec.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public MethodSpec initProtocolFactory(IntermediateModel model) {
    ClassName baseException = baseExceptionClassName(model);
    Metadata metadata = model.getMetadata();
    ParameterizedTypeName upperBound = ParameterizedTypeName.get(ClassName.get(BaseAwsJsonProtocolFactory.Builder.class),
                                                                 TypeVariableName.get("T"));
    TypeVariableName typeVariableName = TypeVariableName.get("T", upperBound);

    MethodSpec.Builder methodSpec = MethodSpec.methodBuilder("init")
                                              .addTypeVariable(typeVariableName)
                                              .addParameter(typeVariableName, "builder")
                                              .returns(typeVariableName)
                                              .addModifiers(Modifier.PRIVATE)
                                              .addCode(
                                                  "return builder\n" +
                                                  ".clientConfiguration(clientConfiguration)\n" +
                                                  ".defaultServiceExceptionSupplier($T::builder)\n" +
                                                  ".protocol($T.$L)\n" +
                                                  ".protocolVersion($S)\n"
                                                  + "$L",
                                                  baseException, AwsJsonProtocol.class,
                                                  protocolEnumName(metadata.getProtocol()), metadata.getJsonVersion(),
                                                  customErrorCodeFieldName());

    if (metadata.getContentType() != null) {
        methodSpec.addCode(".withContentTypeOverride($S)", metadata.getContentType());
    }

    registerModeledExceptions(model, poetExtensions).forEach(methodSpec::addCode);
    methodSpec.addCode(";");

    return methodSpec.build();
}
 
Example 11
Source File: DataLoaderProcessor.java    From DataLoader with Apache License 2.0 5 votes vote down vote up
private TypeName getTypeName(String name) {
    if (name == null || name.length() == 0) {
        return null;
    }
    java.lang.reflect.Type type = getType(name);
    if (type != null) {
        return ClassName.get(type);
    } else {
        return TypeVariableName.get(name);
    }
}
 
Example 12
Source File: AwsServiceModel.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private MethodSpec getterCreator() {
    TypeVariableName t = TypeVariableName.get("T");
    return MethodSpec.methodBuilder("getter")
                     .addTypeVariable(t)
                     .addModifiers(Modifier.PRIVATE, Modifier.STATIC)
                     .addParameter(ParameterizedTypeName.get(ClassName.get(Function.class),
                                                             className(), t),
                                   "g")
                     .returns(ParameterizedTypeName.get(ClassName.get(Function.class),
                                                        ClassName.get(Object.class), t))
                     .addStatement("return obj -> g.apply(($T) obj)", className())
                     .build();
}
 
Example 13
Source File: TupleGenerator.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
private TypeSpec createTuple(int size) {
    String className = CLASS_NAME + size;
    TypeSpec.Builder typeSpecBuilder =
            TypeSpec.classBuilder(className)
                    .addSuperinterface(Tuple.class)
                    .addField(
                            FieldSpec.builder(int.class, SIZE)
                                    .addModifiers(
                                            Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
                                    .initializer("$L", size)
                                    .build());

    MethodSpec.Builder constructorBuilder =
            MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC);

    List<MethodSpec> methodSpecs = new ArrayList<>(size);

    for (int i = 1; i <= size; i++) {
        String value = VALUE + i;
        TypeVariableName typeVariableName = TypeVariableName.get("T" + i);

        typeSpecBuilder
                .addTypeVariable(typeVariableName)
                .addField(typeVariableName, value, Modifier.PRIVATE, Modifier.FINAL);

        constructorBuilder
                .addParameter(typeVariableName, value)
                .addStatement("this.$N = $N", value, value);

        MethodSpec getterSpec =
                MethodSpec.methodBuilder("get" + Strings.capitaliseFirstLetter(value))
                        .addModifiers(Modifier.PUBLIC)
                        .returns(typeVariableName)
                        .addStatement("return $N", value)
                        .build();
        methodSpecs.add(getterSpec);
    }

    MethodSpec constructorSpec = constructorBuilder.build();
    MethodSpec sizeSpec = generateSizeSpec();
    MethodSpec equalsSpec = generateEqualsSpec(className, size);
    MethodSpec hashCodeSpec = generateHashCodeSpec(size);
    MethodSpec toStringSpec = generateToStringSpec(size);

    return typeSpecBuilder
            .addJavadoc(buildWarning(TupleGenerator.class))
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(constructorSpec)
            .addMethods(methodSpecs)
            .addMethod(sizeSpec)
            .addMethod(equalsSpec)
            .addMethod(hashCodeSpec)
            .addMethod(toStringSpec)
            .build();
}
 
Example 14
Source File: PoetUtils.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
public static TypeVariableName createBoundedTypeVariableName(String parameterName, ClassName upperBound,
                                                             String... typeVariables) {
    return TypeVariableName.get(parameterName, createParameterizedTypeName(upperBound, typeVariables));
}
 
Example 15
Source File: TypeCopyableFiller.java    From data-mediator with Apache License 2.0 4 votes vote down vote up
@Override
public void buildMethodStatement(String curPkg, String parentInterfaceName, String curClassName,
                                 ExecutableElement ee, MethodSpec.Builder builder, List<FieldData> list,
                                 boolean hasSuperClass, int superFlagsForParent) {
    final String method = "buildMethodStatement";
    note(method, "start  --------------");

    ClassName parentInterface = ClassName.get(curPkg, parentInterfaceName);
    final TypeName current = TypeVariableName.get(curClassName);
    switch (ee.getSimpleName().toString()){
        /**
        public GoodStudent copy() {
        GoodStudent gs = new GoodStudent();
        copyTo(gs);
        return gs;
        }
         */
        case NAME_COPY:
            builder.addStatement("$T result = new $T()", current, current)
                    .addStatement("this.copyTo(result)")
                    .addStatement("return result");
            break;

        /** //IStudent come from super.
         * public void copyTo(IStudent out) {
             super.copyTo(out);
             if(out instanceof GoodStudent){
                 GoodStudent gs = (GoodStudent) out;
                 gs.setThinking(getThinking());
             }
         }
         */
        case NAME_COPY_TO:
            final String paramName = "out";
            if(hasSuperClass && (superFlagsForParent & getInterfaceFlag()) != 0 ){
                builder.addStatement("super.copyTo($N)", paramName);
            }

            builder.beginControlFlow("if($N instanceof $T)", paramName, parentInterface)
                    .addStatement("$T result = ($T)$N", parentInterface, parentInterface, paramName);
            if(list != null && !list.isEmpty()) {
                for (FieldData fd : list) {
                    note(method," ======= fd = " + fd.getPropertyName());
                    final String nameForMethod = Util.getPropNameForMethod(fd);
                    final String setMethodName = DataMediatorConstants.SET_PREFIX + nameForMethod;
                    final String getMethodName = fd.getGetMethodPrefix() + nameForMethod;
                    builder.addStatement("result.$N(this.$N())", setMethodName, getMethodName);
                }
            }
            builder.endControlFlow();
            break;

        default:
            note("buildMethodStatement","unsupport override : " + ee.getSimpleName().toString());
    }
    note(method, "end  --------------");
}
 
Example 16
Source File: ModelORMInterfaceGenerator.java    From RxAndroidOrm with Apache License 2.0 4 votes vote down vote up
public TypeSpec generate() {
    final TypeVariableName T = TypeVariableName.get("T");
    final TypeName LIST_OF_T = ParameterizedTypeName.get(ClassName.get("java.util", "List"), T);

    final TypeName RETURN_T = ProcessUtils.observableOf(T);
    final TypeName RETURN_LIST_T = ProcessUtils.observableOf(LIST_OF_T);

    return TypeSpec.interfaceBuilder(Constants.DATABASE_COMMON_INTERFACE_NAME)
            .addModifiers(Modifier.PUBLIC)
            .addTypeVariable(T)


            .addMethod(MethodSpec.methodBuilder("select")
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .returns(Constants.queryBuilderClassName)
                    .build())

            .addMethod(MethodSpec.methodBuilder("add")
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .addParameter(T, "object", Modifier.FINAL)
                    .returns(RETURN_T)
                    .build())

            .addMethod(MethodSpec.methodBuilder("add")
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .addParameter(LIST_OF_T, "objects", Modifier.FINAL)
                    .returns(RETURN_LIST_T)
                    .build())

            .addMethod(MethodSpec.methodBuilder("update")
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .addParameter(T, "object", Modifier.FINAL)
                    .returns(RETURN_T)
                    .build())

            .addMethod(MethodSpec.methodBuilder("update")
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .addParameter(LIST_OF_T, "objects", Modifier.FINAL)
                    .returns(RETURN_LIST_T)
                    .build())

            .addMethod(MethodSpec.methodBuilder("delete")
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .addParameter(T, "object", Modifier.FINAL)
                    .returns(ProcessUtils.observableOf(TypeName.BOOLEAN.box()))
                    .build())

            .addMethod(MethodSpec.methodBuilder("delete")
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .addParameter(LIST_OF_T, "objects", Modifier.FINAL)
                    .returns(ProcessUtils.observableOf(TypeName.BOOLEAN.box()))
                    .build())

            .addMethod(MethodSpec.methodBuilder("deleteAll")
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .returns(ProcessUtils.observableOf(TypeName.BOOLEAN.box()))
                    .build())

            .addMethod(MethodSpec.methodBuilder("count")
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .returns(ProcessUtils.observableOf(TypeName.INT.box()))
                    .build())

            .build();
}
 
Example 17
Source File: MethodParamModelUtilsTest.java    From litho with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetTypeVariablesOnTypeVariableName() {
  TypeVariableName type = TypeVariableName.get("T");
  assertThat(MethodParamModelUtils.getTypeVariables(type)).hasSize(1);
  assertThat(MethodParamModelUtils.getTypeVariables(type)).contains(type);
}
 
Example 18
Source File: TupleGenerator.java    From etherscan-explorer with GNU General Public License v3.0 4 votes vote down vote up
private TypeSpec createTuple(int size) {
    String className = CLASS_NAME + size;
    TypeSpec.Builder typeSpecBuilder = TypeSpec.classBuilder(className)
            .addSuperinterface(Tuple.class)
            .addField(FieldSpec.builder(int.class, SIZE)
                    .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
                    .initializer("$L", size)
                    .build());

    MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC);

    List<MethodSpec> methodSpecs = new ArrayList<>(size);

    for (int i = 1; i <= size; i++) {
        String value = VALUE + i;
        TypeVariableName typeVariableName = TypeVariableName.get("T" + i);

        typeSpecBuilder.addTypeVariable(typeVariableName)
                .addField(typeVariableName, value, Modifier.PRIVATE, Modifier.FINAL);

        constructorBuilder.addParameter(typeVariableName, value)
                .addStatement("this.$N = $N", value, value);

        MethodSpec getterSpec = MethodSpec.methodBuilder(
                "get" + Strings.capitaliseFirstLetter(value))
                .addModifiers(Modifier.PUBLIC)
                .returns(typeVariableName)
                .addStatement("return $N", value)
                .build();
        methodSpecs.add(getterSpec);
    }

    MethodSpec constructorSpec = constructorBuilder.build();
    MethodSpec sizeSpec = generateSizeSpec();
    MethodSpec equalsSpec = generateEqualsSpec(className, size);
    MethodSpec hashCodeSpec = generateHashCodeSpec(size);
    MethodSpec toStringSpec = generateToStringSpec(size);

    return typeSpecBuilder
            .addJavadoc(buildWarning(TupleGenerator.class))
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(constructorSpec)
            .addMethods(methodSpecs)
            .addMethod(sizeSpec)
            .addMethod(equalsSpec)
            .addMethod(hashCodeSpec)
            .addMethod(toStringSpec)
            .build();
}
 
Example 19
Source File: TupleGenerator.java    From client-sdk-java with Apache License 2.0 4 votes vote down vote up
private TypeSpec createTuple(int size) {
    String className = CLASS_NAME + size;
    TypeSpec.Builder typeSpecBuilder = TypeSpec.classBuilder(className)
            .addSuperinterface(Tuple.class)
            .addField(FieldSpec.builder(int.class, SIZE)
                    .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
                    .initializer("$L", size)
                    .build());

    MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC);

    List<MethodSpec> methodSpecs = new ArrayList<>(size);

    for (int i = 1; i <= size; i++) {
        String value = VALUE + i;
        TypeVariableName typeVariableName = TypeVariableName.get("T" + i);

        typeSpecBuilder.addTypeVariable(typeVariableName)
                .addField(typeVariableName, value, Modifier.PRIVATE, Modifier.FINAL);

        constructorBuilder.addParameter(typeVariableName, value)
                .addStatement("this.$N = $N", value, value);

        MethodSpec getterSpec = MethodSpec.methodBuilder(
                "get" + Strings.capitaliseFirstLetter(value))
                .addModifiers(Modifier.PUBLIC)
                .returns(typeVariableName)
                .addStatement("return $N", value)
                .build();
        methodSpecs.add(getterSpec);
    }

    MethodSpec constructorSpec = constructorBuilder.build();
    MethodSpec sizeSpec = generateSizeSpec();
    MethodSpec equalsSpec = generateEqualsSpec(className, size);
    MethodSpec hashCodeSpec = generateHashCodeSpec(size);
    MethodSpec toStringSpec = generateToStringSpec(size);

    return typeSpecBuilder
            .addJavadoc(buildWarning(TupleGenerator.class))
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(constructorSpec)
            .addMethods(methodSpecs)
            .addMethod(sizeSpec)
            .addMethod(equalsSpec)
            .addMethod(hashCodeSpec)
            .addMethod(toStringSpec)
            .build();
}
 
Example 20
Source File: OperatorProcessor.java    From java with Apache License 2.0 4 votes vote down vote up
private MethodSpec buildOpMethod(
    String methodName, TypeElement opClass, ExecutableElement endpointMethod,
    boolean describeByClass, boolean deprecated) {
  MethodSpec.Builder builder =
      MethodSpec.methodBuilder(methodName)
          .addModifiers(Modifier.PUBLIC)
          .returns(TypeName.get(endpointMethod.getReturnType()))
          .varargs(endpointMethod.isVarArgs())
          .addJavadoc("$L", buildOpMethodJavadoc(opClass, endpointMethod, describeByClass));

  if (deprecated) {
    builder.addAnnotation(Deprecated.class);
  }
  for (TypeParameterElement tp : endpointMethod.getTypeParameters()) {
    TypeVariableName tvn = TypeVariableName.get((TypeVariable) tp.asType());
    builder.addTypeVariable(tvn);
  }
  for (TypeMirror thrownType : endpointMethod.getThrownTypes()) {
    builder.addException(TypeName.get(thrownType));
  }
  StringBuilder call = new StringBuilder();
  if (!NoType.class.isAssignableFrom(endpointMethod.getReturnType().getClass())) {
    call.append("return ");
  }
  call.append("$T.")
    .append(endpointMethod.getSimpleName())
    .append("(scope");
  boolean first = true;
  for (VariableElement param : endpointMethod.getParameters()) {
    ParameterSpec p = ParameterSpec.get(param);
    if (first) {
      first = false;
      continue;
    }
    call.append(", ");
    call.append(p.name);
    builder.addParameter(p);
  }
  call.append(")");
  builder.addStatement(call.toString(), ClassName.get(opClass));
  return builder.build();
}