com.squareup.javapoet.ParameterSpec Java Examples

The following examples show how to use com.squareup.javapoet.ParameterSpec. 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: SensorAnnotationsFileBuilder.java    From SensorAnnotations with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the implementation of {@code SensorEventListener#onSensorChanged(SensorEvent)} which
 * calls the annotated method on our target class.
 *
 * @param annotatedMethod Method annotated with {@code OnSensorChanged}.
 * @return {@link MethodSpec} of {@code SensorEventListener#onSensorChanged(SensorEvent)}.
 */
@NonNull
private static MethodSpec createOnSensorChangedListenerMethod(
    @Nullable AnnotatedMethod annotatedMethod) {
    ParameterSpec sensorEventParameter = ParameterSpec.builder(SENSOR_EVENT, "event").build();
    Builder methodBuilder =
        getBaseMethodBuilder("onSensorChanged").addParameter(sensorEventParameter);

    if (annotatedMethod != null) {
        ExecutableElement sensorChangedExecutableElement =
            annotatedMethod.getExecutableElement();
        methodBuilder.addStatement("target.$L($N)",
            sensorChangedExecutableElement.getSimpleName(), sensorEventParameter);
    }

    return methodBuilder.build();
}
 
Example #2
Source File: JavaFiler.java    From convalida with Apache License 2.0 6 votes vote down vote up
private static MethodSpec createInitDatabindingMethod(ValidationClass validationClass) {
    ClassName className = ClassName.get(validationClass.packageName, validationClass.className);
    return MethodSpec.methodBuilder("init")
            .addModifiers(PUBLIC, STATIC)
            .addAnnotation(UI_THREAD)
            .addParameter(ParameterSpec
                    .builder(validationClass.typeName, "target")
                    .addAnnotation(NON_NULL)
                    .build()
            )
            .addParameter(ParameterSpec
                    .builder(VIEW_DATA_BINDING, "binding")
                    .addAnnotation(NON_NULL)
                    .build()
            )
            .addStatement("new $T(target, binding)", className)
            .build();
}
 
Example #3
Source File: Parcelables.java    From auto-parcel with Apache License 2.0 6 votes vote down vote up
public static CodeBlock writeValueWithTypeAdapter(FieldSpec adapter, AutoParcelProcessor.Property p, ParameterSpec out) {
    CodeBlock.Builder block = CodeBlock.builder();

    if (p.isNullable()) {
        block.beginControlFlow("if ($N == null)", p.fieldName);
        block.addStatement("$N.writeInt(1)", out);
        block.nextControlFlow("else");
        block.addStatement("$N.writeInt(0)", out);
    }

    block.addStatement("$N.toParcel($N, $N)", adapter, p.fieldName, out);

    if (p.isNullable()) {
        block.endControlFlow();
    }

    return block.build();
}
 
Example #4
Source File: NotNullValidatorTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Test
public void addValueSpaceCheck() throws Exception {
    ParameterSpec paramS = ParameterSpec.builder(ClassName.get(String.class), "s")
                                        .build();

    MethodSpec.Builder method = MethodSpec.methodBuilder("foo")
            .addModifiers(Modifier.PUBLIC)
            .addParameter(paramS)
            .returns(void.class);

    NotNullValidator validator = new NotNullValidator();
    validator.addValueSpaceCheck(method, paramS, rdfsClazz);

    String code = method.build().code.toString();
    Matcher matcher = Pattern.compile("if\\s*\\((s\\s*==\\s*null|null\\s*==\\s*s)\\)").matcher(code);
    assertTrue(matcher.find());
}
 
Example #5
Source File: BuilderGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
private static MethodSpec generateEventDeclarationBuilderMethod(
    SpecModel specModel, EventDeclarationModel eventDeclaration) {
  final String eventHandlerName =
      ComponentBodyGenerator.getEventHandlerInstanceName(eventDeclaration.name);
  return MethodSpec.methodBuilder(eventHandlerName)
      .addModifiers(Modifier.PUBLIC)
      .returns(getBuilderType(specModel))
      .addParameter(
          ParameterSpec.builder(ClassNames.EVENT_HANDLER, eventHandlerName)
              .addAnnotation(ClassNames.NULLABLE)
              .build())
      .addStatement(
          "this.$L.$L = $L",
          getComponentMemberInstanceName(specModel),
          eventHandlerName,
          eventHandlerName)
      .addStatement("return this")
      .build();
}
 
Example #6
Source File: GremlinDslProcessor.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private void addMethodBody(final MethodSpec.Builder methodToAdd, final ExecutableElement templateMethod,
                           final String startBody, final String endBody, final Object... statementArgs) {
    final List<? extends VariableElement> parameters = templateMethod.getParameters();
    final StringBuilder body = new StringBuilder(startBody);

    final int numberOfParams = parameters.size();
    for (int ix = 0; ix < numberOfParams; ix++) {
        final VariableElement param = parameters.get(ix);
        methodToAdd.addParameter(ParameterSpec.get(param));
        body.append(param.getSimpleName());
        if (ix < numberOfParams - 1) {
            body.append(",");
        }
    }

    body.append(endBody);

    // treat a final array as a varargs param
    if (!parameters.isEmpty() && parameters.get(parameters.size() - 1).asType().getKind() == TypeKind.ARRAY)
        methodToAdd.varargs(true);

    methodToAdd.addStatement(body.toString(), statementArgs);
}
 
Example #7
Source File: SensorAnnotationsFileBuilder.java    From SensorAnnotations with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the implementation of {@code SensorEventListener#onAccuracyChanged(Sensor, int)}
 * which calls the annotated method on our target class.
 *
 * @param annotatedMethod Method annotated with {@link OnAccuracyChanged}.
 * @return {@link MethodSpec} of {@code SensorEventListener#onAccuracyChanged(Sensor, int)}.
 */
@NonNull
private static MethodSpec createOnAccuracyChangedListenerMethod(
    @Nullable AnnotatedMethod annotatedMethod) {
    ParameterSpec sensorParameter = ParameterSpec.builder(SENSOR, "sensor").build();
    ParameterSpec accuracyParameter = ParameterSpec.builder(TypeName.INT, "accuracy").build();
    Builder methodBuilder =
        getBaseMethodBuilder("onAccuracyChanged").addParameter(sensorParameter)
            .addParameter(accuracyParameter);

    if (annotatedMethod != null) {
        ExecutableElement accuracyChangedExecutableElement =
            annotatedMethod.getExecutableElement();
        methodBuilder.addStatement("target.$L($N, $N)",
            accuracyChangedExecutableElement.getSimpleName(), sensorParameter,
            accuracyParameter);
    }

    return methodBuilder.build();
}
 
Example #8
Source File: EventGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
/** Generate a dispatchOnEvent() implementation for the component. */
static MethodSpec generateDispatchOnEvent(SpecModel specModel) {
  final MethodSpec.Builder methodBuilder =
      MethodSpec.methodBuilder("dispatchOnEvent")
          .addModifiers(Modifier.PUBLIC)
          .addAnnotation(Override.class)
          .returns(TypeName.OBJECT)
          .addParameter(
              ParameterSpec.builder(EVENT_HANDLER, "eventHandler", Modifier.FINAL).build())
          .addParameter(ParameterSpec.builder(OBJECT, "eventState", Modifier.FINAL).build());

  methodBuilder.addStatement("int id = eventHandler.id");
  methodBuilder.beginControlFlow("switch ($L)", "id");

  EventCaseGenerator.builder()
      .contextClass(specModel.getContextClass())
      .eventMethodModels(specModel.getEventMethods())
      // For now, Sections are not supported for error propagation
      .withErrorPropagation(specModel.getComponentClass().equals(ClassNames.COMPONENT))
      .writeTo(methodBuilder);

  return methodBuilder.addStatement("default:\nreturn null").endControlFlow().build();
}
 
Example #9
Source File: ViewStateClassGenerator.java    From Moxy with MIT License 6 votes vote down vote up
private MethodSpec generateCommandConstructor(ViewMethod method) {
	List<ParameterSpec> parameters = method.getParameterSpecs();

	MethodSpec.Builder builder = MethodSpec.constructorBuilder()
			.addParameters(parameters)
			.addStatement("super($S, $T.class)", method.getTag(), method.getStrategy());

	if (parameters.size() > 0) {
		builder.addCode("\n");
	}

	for (ParameterSpec parameter : parameters) {
		builder.addStatement("this.$1N = $1N", parameter);
	}

	return builder.build();
}
 
Example #10
Source File: ModuleGenerator.java    From nalu with Apache License 2.0 6 votes vote down vote up
private void generateLoadFilters(TypeSpec.Builder typeSpec) {
  // method must always be created!
  MethodSpec.Builder loadFiltersMethod = MethodSpec.methodBuilder("loadFilters")
                                                   .addAnnotation(Override.class)
                                                   .addModifiers(Modifier.PUBLIC)
                                                   .addParameter(ParameterSpec.builder(ClassName.get(RouterConfiguration.class),
                                                                                       "routerConfiguration")
                                                                              .build());

  this.metaModel.getFilters()
                .forEach(classNameModel -> loadFiltersMethod.addStatement("$T $L = new $T()",
                                                                          ClassName.get(classNameModel.getPackage(),
                                                                                        classNameModel.getSimpleName()),
                                                                          this.processorUtils.createFullClassName(classNameModel.getClassName()),
                                                                          ClassName.get(classNameModel.getPackage(),
                                                                                        classNameModel.getSimpleName()))
                                                            .addStatement("$L.setContext(super.moduleContext)",
                                                                          this.processorUtils.createFullClassName(classNameModel.getClassName()))
                                                            .addStatement("routerConfiguration.getFilters().add($L)",
                                                                          this.processorUtils.createFullClassName(classNameModel.getClassName()))
                                                            .addStatement("$T.get().logDetailed(\"AbstractApplication: filter >> $L << created\", 0)",
                                                                          ClassName.get(ClientLogger.class),
                                                                          this.processorUtils.createFullClassName(classNameModel.getClassName())));

  typeSpec.addMethod(loadFiltersMethod.build());
}
 
Example #11
Source File: ControllerCreatorGenerator.java    From nalu with Apache License 2.0 6 votes vote down vote up
private MethodSpec createConstructor() {
  return MethodSpec.constructorBuilder()
                   .addModifiers(Modifier.PUBLIC)
                   .addParameter(ParameterSpec.builder(ClassName.get(Router.class),
                                                       "router")
                                              .build())
                   .addParameter(ParameterSpec.builder(controllerModel.getContext()
                                                                      .getTypeName(),
                                                       "context")
                                              .build())
                   .addParameter(ParameterSpec.builder(ClassName.get(SimpleEventBus.class),
                                                       "eventBus")
                                              .build())
                   .addStatement("super(router, context, eventBus)")
                   .build();
}
 
Example #12
Source File: BundleBindingAdapterGenerator.java    From pocketknife with Apache License 2.0 6 votes vote down vote up
private void addBindingArgumentsMethod(TypeSpec.Builder classBuilder, TypeVariableName t) {
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(BIND_ARGUMENTS_METHOD)
            .addModifiers(PUBLIC)
            .addParameter(ParameterSpec.builder(t, TARGET).build())
            .addParameter(ParameterSpec.builder(ClassName.get(typeUtil.bundleType), BUNDLE).build());
    if (parentAdapter != null) {
        methodBuilder.addStatement(SUPER_METHOD_TEMPLATE, BIND_ARGUMENTS_METHOD, TARGET, BUNDLE);
    }
    methodBuilder.beginControlFlow("if ($N == null)", BUNDLE);
    if (required) {
        methodBuilder.addStatement(THROW_NEW_DOLLAR_SIGN_T_PARENTHESES_DOLLAR_SIGN_S_PARENTHESES, IllegalStateException.class, "Argument bundle is null");
    } else {
        methodBuilder.addStatement("$N = new $T()", BUNDLE, ClassName.get(typeUtil.bundleType));
    }
    methodBuilder.endControlFlow();
    for (BundleFieldBinding field : fields) {
        if (ARGUMENT == field.getAnnotationType()) {
            addGetArgumentStatement(methodBuilder, field);
        }
    }
    classBuilder.addMethod(methodBuilder.build());
}
 
Example #13
Source File: PreferenceComponentGenerator.java    From PreferenceRoom with Apache License 2.0 6 votes vote down vote up
private MethodSpec getConstructorSpec() {
  MethodSpec.Builder builder =
      MethodSpec.constructorBuilder()
          .addModifiers(PRIVATE)
          .addParameter(
              ParameterSpec.builder(getContextPackageType(), CONSTRUCTOR_CONTEXT)
                  .addAnnotation(NonNull.class)
                  .build());

  this.annotatedClazz.keyNames.forEach(
      keyName ->
          builder.addStatement(
              "$N = $N.getInstance($N.getApplicationContext())",
              getEntityInstanceFieldName(keyName),
              getEntityClazzName(annotatedEntityMap.get(keyName)),
              CONSTRUCTOR_CONTEXT));

  return builder.build();
}
 
Example #14
Source File: MatchMethods.java    From dataenum with Apache License 2.0 6 votes vote down vote up
private MethodSpec.Builder createFoldVoidSignature(
    Iterable<TypeVariableName> availableTypeVariables) throws ParserException {
  MethodSpec.Builder builder =
      MethodSpec.methodBuilder("match").addModifiers(Modifier.PUBLIC).returns(void.class);

  for (OutputValue arg : values) {
    TypeName visitor =
        ParameterizedTypeName.get(
            ClassName.get(Consumer.class),
            withoutMissingTypeVariables(arg.parameterizedOutputClass(), availableTypeVariables));

    builder.addParameter(
        ParameterSpec.builder(visitor, asCamelCase(arg.name()))
            .addAnnotation(Nonnull.class)
            .build());
  }

  return builder;
}
 
Example #15
Source File: BaseDecorator.java    From EasyMVP with Apache License 2.0 6 votes vote down vote up
private MethodSpec getInitializeMethodWithFactory() {
    MethodSpec.Builder method = MethodSpec.methodBuilder(METHOD_INITIALIZE)
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(Override.class)
            .addParameter(delegateClassGenerator.getViewClass(), "view")
            .returns(TypeName.VOID);

    method.addParameter(ParameterSpec.builder(presenterFactoryTypeName(), "presenterFactory",
            Modifier.FINAL).build());
    if (!delegateClassGenerator.isInjectablePresenterInView()) {
        method.addStatement("// Intentionally left blank!");
    } else {
        initLoader(method, "presenterFactory");
        implementInitializer(method);
    }
    return method.build();
}
 
Example #16
Source File: ViewMethod.java    From Moxy with MIT License 5 votes vote down vote up
ViewMethod(ExecutableElement methodElement,
           TypeElement strategy,
           String tag) {
	this.element = methodElement;
	this.name = methodElement.getSimpleName().toString();
	this.strategy = strategy;
	this.tag = tag;

	this.parameterSpecs = methodElement.getParameters()
			.stream()
			.map(ParameterSpec::get)
			.collect(Collectors.toList());

	this.exceptions = methodElement.getThrownTypes().stream()
			.map(TypeName::get)
			.collect(Collectors.toList());

	this.typeVariables = methodElement.getTypeParameters()
			.stream()
			.map(TypeVariableName::get)
			.collect(Collectors.toList());

	this.argumentsString = parameterSpecs.stream()
			.map(parameterSpec -> parameterSpec.name)
			.collect(Collectors.joining(", "));

	this.uniqueSuffix = "";
}
 
Example #17
Source File: PreferenceComponentGenerator.java    From PreferenceRoom with Apache License 2.0 5 votes vote down vote up
private MethodSpec getInitializeSpec() {
  return MethodSpec.methodBuilder("init")
      .addModifiers(PUBLIC, STATIC)
      .addParameter(
          ParameterSpec.builder(getContextPackageType(), CONSTRUCTOR_CONTEXT)
              .addAnnotation(NonNull.class)
              .build())
      .addStatement("if($N != null) return $N", FIELD_INSTANCE, FIELD_INSTANCE)
      .addStatement("$N = new $N($N)", FIELD_INSTANCE, getClazzName(), CONSTRUCTOR_CONTEXT)
      .addStatement("return $N", FIELD_INSTANCE)
      .returns(getClassType())
      .build();
}
 
Example #18
Source File: MatcherGenerator.java    From litho with Apache License 2.0 5 votes vote down vote up
private static MethodSpec matcherFieldSetterBuilder(SpecModel specModel, PropModel prop) {
  final String propMatcherName = getPropMatcherName(prop);
  final String propName = prop.getName();

  return getMethodSpecBuilder(
          specModel,
          ImmutableList.of(ParameterSpec.builder(getPropMatcherType(prop), "matcher").build()),
          CodeBlock.builder()
              .addStatement(
                  "$L = ($L) matcher", propMatcherName, getPropMatcherType(prop).toString())
              .build(),
          propName)
      .build();
}
 
Example #19
Source File: RouterTaskCodeBuilder.java    From grouter-android with Apache License 2.0 5 votes vote down vote up
private static void addMethodSpec(TypeSpec.Builder typeSpec, ClassName className, ParameterModel typeMember) {
    TypeName typeName = TypeUtils.getTypeName(typeMember.type);
    ParameterSpec parameterSpec = ParameterSpec.builder(typeName, typeMember.name).build();
    MethodSpec methodSpec = MethodSpec.methodBuilder(typeMember.name)
            .addModifiers(Modifier.PUBLIC)
            .addParameter(parameterSpec)
            .addStatement("put($S,$N)", typeMember.name, typeMember.name)
            .addStatement("return this")
            .returns(className)
            .build();
    typeSpec.addMethod(methodSpec);
}
 
Example #20
Source File: MethodSpecGenerator.java    From web3j with Apache License 2.0 5 votes vote down vote up
public MethodSpecGenerator(
        String testMethodName,
        Map<String, Object[]> statementBody,
        List<ParameterSpec> testMethodParameters) {
    this.statementBody = statementBody;
    this.testMethodName = testMethodName;
    this.testMethodAnnotation = Test.class;
    this.testMethodModifier = Modifier.PUBLIC;
    this.testMethodParameters = testMethodParameters;
}
 
Example #21
Source File: ResourceMethodExtensionPlugin.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
private Builder addAnnotations(GMethod method, MethodSpec.Builder methodSpec) {
  MethodSpec.Builder ret = cloneMethodWithoutParams(methodSpec);

  MethodSpec spec = methodSpec.build();

  List<ParameterSpec> modifiedParams = new ArrayList<>(spec.parameters);
  Iterator<GParameter> methodParams = method.queryParameters().iterator();

  for (int j = 0; j < modifiedParams.size(); j++) {
    ParameterSpec orgParam = modifiedParams.get(j);
    List<AnnotationSpec> an = orgParam.annotations;
    for (AnnotationSpec a : an) {
      if (a.type.toString().equals("javax.ws.rs.QueryParam")) {
        modifiedParams.set(j, annotateNew(methodParams.next(), orgParam));
      }
      if (a.type.toString().equals("javax.ws.rs.PathParam")) {
        GResource curRes = method.resource();
        while (curRes != null) {
          for (GParameter u : curRes.uriParameters()) {
            if (u.name().equals(orgParam.name)) {
              modifiedParams.set(j, annotateNew(u, orgParam));
            }
          }
          curRes = curRes.parentResource();
        }
      }
    }
  }
  ret.addParameters(modifiedParams);
  return ret;
}
 
Example #22
Source File: ListSetters.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private MethodSpec fluentVarargToListSetter(TypeName returnType) {
    return fluentSetterBuilder(ParameterSpec.builder(asArray(), fieldName()).build(), returnType)
            .varargs(true)
            .addAnnotation(SafeVarargs.class)
            .addCode(varargToListSetterBody())
            .addStatement("return this")
            .build();
}
 
Example #23
Source File: PassCreate.java    From soabase-halva with Apache License 2.0 5 votes vote down vote up
void addDelegation(TypeSpec.Builder builder, ClassName aliasClassName, DeclaredType parentType)
{
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(aliasClassName.simpleName())
        .returns(aliasClassName)
        .addParameter(ParameterSpec.builder(ClassName.get(parentType), "instance").build())
        .addModifiers(Modifier.STATIC, Modifier.PUBLIC)
        ;

    CodeBlock returnBlock = CodeBlock.builder()
        .addStatement("return $L", buildProxy(parentType, aliasClassName))
        .build();
    methodBuilder.addCode(returnBlock);

    builder.addMethod(methodBuilder.build());
}
 
Example #24
Source File: ComponentProcessing.java    From Auto-Dagger2 with MIT License 5 votes vote down vote up
private List<MethodSpec> getSubcomponents() {
    if (extractor.getSubcomponentsTypeMirrors().isEmpty()) {
        return Collections.emptyList();
    }

    List<MethodSpec> methodSpecs = new ArrayList<>(extractor.getSubcomponentsTypeMirrors().size());
    for (TypeMirror typeMirror : extractor.getSubcomponentsTypeMirrors()) {
        Element e = MoreTypes.asElement(typeMirror);
        TypeName typeName;
        String name;
        if (MoreElements.isAnnotationPresent(e, AutoSubcomponent.class)) {
            ClassName cls = AutoComponentClassNameUtil.getComponentClassName(e);
            typeName = cls;
            name = cls.simpleName();
        } else {
            typeName = TypeName.get(typeMirror);
            name = e.getSimpleName().toString();
        }

        List<TypeMirror> modules = state.getSubcomponentModules(typeMirror);
        List<ParameterSpec> parameterSpecs;
        if(modules != null) {
            parameterSpecs = new ArrayList<>(modules.size());
            int count = 0;
            for (TypeMirror moduleTypeMirror : modules) {
                parameterSpecs.add(ParameterSpec.builder(TypeName.get(moduleTypeMirror), String.format("module%d", ++count)).build());
            }
        } else {
            parameterSpecs = new ArrayList<>(0);
        }

        methodSpecs.add(MethodSpec.methodBuilder("plus" + name)
                .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                .addParameters(parameterSpecs)
                .returns(typeName)
                .build());
    }

    return methodSpecs;
}
 
Example #25
Source File: DelegateMethodDescriptions.java    From litho with Apache License 2.0 5 votes vote down vote up
private static MethodSpec getService(String implClass, String serviceInstanceName) {
  return MethodSpec.methodBuilder("getService")
      .addAnnotation(Override.class)
      .addModifiers(Modifier.PROTECTED)
      .returns(TypeName.OBJECT)
      .addParameter(ParameterSpec.builder(SectionClassNames.SECTION, "section").build())
      .addStatement("return (($L) section).$L", implClass, serviceInstanceName)
      .build();
}
 
Example #26
Source File: DelegateMethodDescriptions.java    From litho with Apache License 2.0 5 votes vote down vote up
private static MethodSpec transferService(String implClass, String serviceInstanceName) {
  return MethodSpec.methodBuilder("transferService")
      .addAnnotation(Override.class)
      .returns(TypeName.VOID)
      .addModifiers(Modifier.PROTECTED)
      .addParameter(ParameterSpec.builder(SectionClassNames.SECTION_CONTEXT, "c").build())
      .addParameter(ParameterSpec.builder(SectionClassNames.SECTION, "previous").build())
      .addParameter(ParameterSpec.builder(SectionClassNames.SECTION, "next").build())
      .addStatement("$L $L = ($L) previous", implClass, "previousSection", implClass)
      .addStatement("$L $L = ($L) next", implClass, "nextSection", implClass)
      .addStatement(
          "nextSection.$L = previousSection.$L", serviceInstanceName, serviceInstanceName)
      .build();
}
 
Example #27
Source File: ClientClassUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
static MethodSpec consumerBuilderVariant(MethodSpec spec, String javadoc) {
    Validate.validState(spec.parameters.size() > 0, "A first parameter is required to generate a consumer-builder method.");
    Validate.validState(spec.parameters.get(0).type instanceof ClassName, "The first parameter must be a class.");

    ParameterSpec firstParameter = spec.parameters.get(0);
    ClassName firstParameterClass = (ClassName) firstParameter.type;
    TypeName consumer = ParameterizedTypeName.get(ClassName.get(Consumer.class), firstParameterClass.nestedClass("Builder"));

    MethodSpec.Builder result = MethodSpec.methodBuilder(spec.name)
                                          .returns(spec.returnType)
                                          .addExceptions(spec.exceptions)
                                          .addJavadoc(javadoc)
                                          .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT)
                                          .addTypeVariables(spec.typeVariables)
                                          .addParameter(ParameterSpec.builder(consumer, firstParameter.name).build());


    // Parameters
    StringBuilder methodBody = new StringBuilder("return $L($T.builder().applyMutation($L).build()");
    for (int i = 1; i < spec.parameters.size(); i++) {
        ParameterSpec parameter = spec.parameters.get(i);
        methodBody.append(", ").append(parameter.name);
        result.addParameter(parameter);
    }
    methodBody.append(")");

    result.addStatement(methodBody.toString(), spec.name, firstParameterClass, firstParameter.name);

    return result.build();
}
 
Example #28
Source File: FeatureCodeBrewer.java    From featured with Apache License 2.0 5 votes vote down vote up
private void brewMethodWithFeature(FeatureNode featureNode) {
    MethodSpec.Builder withMethod = MethodSpec.methodBuilder("with")
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(mNames.getNonNullClassName())
            .addParameter(ParameterSpec.builder(mFeatureClassName, "feature")
                    .addAnnotation(mNames.getNonNullClassName())
                    .build());

    TypeName featureHostType = mNames.getFeatureHostParameterTypeName(featureNode);

    if (featureHostType == null) {
        withMethod.addCode(CodeBlock.builder()
                .addStatement("addFeature(feature, feature.getClass().toString())")
                .addStatement("return this")
                .build())
                .returns(mFeatureHostClassName);

    } else {
        withMethod.addCode(CodeBlock.builder()
                .addStatement("addFeature(feature, feature.getClass().toString())")
                .addStatement("return ($T) this", featureHostType)
                .build())
                .returns(featureHostType);
    }

    mFeatureHostTypeBuilder
            .addMethod(withMethod.build());
}
 
Example #29
Source File: AnnotatedClass.java    From AndroidQuick with MIT License 5 votes vote down vote up
JavaFile generateFile() {
    //方法参数类型
    ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(
            ClassName.get(Map.class),
            ClassName.get(String.class),
            ClassName.get(TagInfo.class));
    ParameterSpec params = ParameterSpec.builder(parameterizedTypeName, "params").build();

    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("load")
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(Override.class)
            .addParameter(params);

    for (BindTagField item : mFields) {
        String key = item.getTypeName().toString();
        TagInfo.Type type = item.getType();
        String[] value = item.getTag();
        String description = item.getDescription();
        // 添加方法内容
        methodBuilder.addStatement("params.put($S,$T.build($T.$L,$S,$S,$S))",
                key,
                ClassName.get(TagInfo.class),
                ClassName.get(TagInfo.Type.class),
                type,
                key,
                Arrays.toString(value),
                description);
    }
    //生成类
    TypeSpec finderClass = TypeSpec.classBuilder("TagService")
            .addSuperinterface(ClassName.get("com.androidwind.annotation.core", "ILoad"))
            .addModifiers(Modifier.PUBLIC)
            .addMethod(methodBuilder.build())
            .build();

    return JavaFile.builder("com.androidwind.annotation", finderClass).build();
}
 
Example #30
Source File: OpenApiClientGenerator.java    From spring-openapi with MIT License 5 votes vote down vote up
private void enrichWithGetSet(TypeSpec.Builder typeSpecBuilder, ClassName className, String fieldName) {
	typeSpecBuilder.addMethod(MethodSpec.methodBuilder("set" + StringUtils.capitalize(fieldName))
			.addParameter(ParameterSpec.builder(className, fieldName).build())
			.addModifiers(Modifier.PUBLIC)
			.addStatement(String.format("this.%s = %s", fieldName, fieldName))
			.returns(TypeName.VOID)
			.build());
	typeSpecBuilder.addMethod(MethodSpec.methodBuilder("get" + StringUtils.capitalize(fieldName))
			.addModifiers(Modifier.PUBLIC)
			.addStatement(String.format("return this.%s", fieldName))
			.returns(className)
			.build());
}