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 Project: PreferenceRoom   Author: skydoves   File: PreferenceComponentGenerator.java    License: 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 #2
Source Project: SensorAnnotations   Author: dvoiss   File: SensorAnnotationsFileBuilder.java    License: 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 #3
Source Project: SensorAnnotations   Author: dvoiss   File: SensorAnnotationsFileBuilder.java    License: 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 #4
Source Project: auto-parcel   Author: aitorvs   File: Parcelables.java    License: 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 #5
Source Project: convalida   Author: wellingtoncosta   File: JavaFiler.java    License: 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 #6
Source Project: tinkerpop   Author: apache   File: GremlinDslProcessor.java    License: 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 Project: dataenum   Author: spotify   File: MatchMethods.java    License: 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 #8
Source Project: nalu   Author: NaluKit   File: ControllerCreatorGenerator.java    License: 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 #9
Source Project: nalu   Author: NaluKit   File: ModuleGenerator.java    License: 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 #10
Source Project: anno4j   Author: anno4j   File: NotNullValidatorTest.java    License: 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 #11
Source Project: litho   Author: facebook   File: BuilderGenerator.java    License: 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 #12
Source Project: litho   Author: facebook   File: EventGenerator.java    License: 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 #13
Source Project: Moxy   Author: Arello-Mobile   File: ViewStateClassGenerator.java    License: 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 #14
Source Project: pocketknife   Author: hansenji   File: BundleBindingAdapterGenerator.java    License: 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 #15
Source Project: EasyMVP   Author: 6thsolution   File: BaseDecorator.java    License: 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 Project: requery   Author: requery   File: EntityGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generateConstructors(TypeSpec.Builder builder) {
    // copy the existing constructors
    for (ExecutableElement constructor : ElementFilter.constructorsIn(
            typeElement.getEnclosedElements())) {
        // constructor params
        List<? extends VariableElement> parameters = constructor.getParameters();

        if (!parameters.isEmpty()) {

            MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder();
            constructorBuilder.addModifiers(constructor.getModifiers());

            List<String> parameterNames = new ArrayList<>();
            for (VariableElement parameter : parameters) {
                Modifier[] modifiers = parameter.getModifiers().toArray(
                        new Modifier[parameter.getModifiers().size()]);
                String parameterName = parameter.getSimpleName().toString();
                parameterNames.add(parameterName);
                ParameterSpec.Builder parameterBuilder = ParameterSpec.builder(
                        TypeName.get(parameter.asType()), parameterName, modifiers);
                constructorBuilder.addParameter(parameterBuilder.build());
            }
            // super parameter/arguments
            StringJoiner joiner = new StringJoiner(",", "(", ")");
            parameterNames.forEach(joiner::add);
            constructorBuilder.addStatement("super" + joiner.toString());
            builder.addMethod(constructorBuilder.build());
        }
    }
}
 
Example #17
Source Project: spring-openapi   Author: jrcodeza   File: OpenApiClientGenerator.java    License: 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());
}
 
Example #18
Source Project: convalida   Author: wellingtoncosta   File: JavaFiler.java    License: Apache License 2.0 5 votes vote down vote up
private static MethodSpec createInitMethod(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()
            )
            .addStatement("new $T(target)", className)
            .build();
}
 
Example #19
Source Project: spring-openapi   Author: jrcodeza   File: ResourceInterfaceGenerator.java    License: MIT License 5 votes vote down vote up
private ParameterSpec.Builder parseProperties(String parameterName, Schema parameterSchema) {
	if (parameterSchema.getType() != null) {
		return parseTypeBasedSchema(parameterName, parameterSchema);
	} else if (parameterSchema.get$ref() != null) {
		// simple no inheritance
		return createSimpleParameterSpec(null, getNameFromRef(parameterSchema.get$ref()), parameterName);
	} else if (parameterSchema instanceof ComposedSchema && CollectionUtils.isNotEmpty(((ComposedSchema) parameterSchema).getAllOf())) {
		return createSimpleParameterSpec(null, determineParentClassNameUsingOneOf(parameterSchema, parameterName, allComponents), parameterName);
	} else {
		throw new IllegalArgumentException("Incorrect schema. One of [type, $ref, discriminator+oneOf] has to be defined in property schema");
	}
}
 
Example #20
Source Project: vault   Author: contentful   File: ModelInjection.java    License: Apache License 2.0 5 votes vote down vote up
private void appendSetField(TypeSpec.Builder builder) {
  MethodSpec.Builder method = MethodSpec.methodBuilder("setField")
      .addAnnotation(Override.class)
      .addAnnotation(
          AnnotationSpec.builder(SuppressWarnings.class)
              .addMember("value", "$S", "unchecked")
              .build())
      .addModifiers(Modifier.PUBLIC)
      .returns(boolean.class)
      .addParameter(ParameterSpec.builder(ClassName.get(originatingElement), "resource").build())
      .addParameter(ParameterSpec.builder(ClassName.get(String.class), "name").build())
      .addParameter(ParameterSpec.builder(ClassName.get(Object.class), "value").build());

  FieldMeta[] array = fields.toArray(new FieldMeta[fields.size()]);
  for (int i = 0; i < array.length; i++) {
    FieldMeta field = array[i];
    if (i == 0) {
      method.beginControlFlow("if ($S.equals(name))", field.name());
    } else {
      method.endControlFlow().beginControlFlow("else if ($S.equals(name))", field.name());
    }
    method.addStatement("resource.$L = ($T) value", field.name(), field.type());
  }
  method.endControlFlow()
      .beginControlFlow("else")
        .addStatement("return false")
      .endControlFlow()
      .addStatement("return true");

  builder.addMethod(method.build());
}
 
Example #21
Source Project: AutoBundle   Author: yatatsu   File: AutoBundleWriter.java    License: Apache License 2.0 5 votes vote down vote up
private static MethodSpec createBuilderConstructor(AutoBundleBindingClass target,
                                                   String fieldName) {
    MethodSpec.Builder builder = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addStatement("this.$N = new $T()", fieldName, CLASS_BUNDLE);

    for (AutoBundleBindingField arg : target.getRequiredArgs()) {
        String key = arg.getArgKey();
        TypeName type = arg.getArgType();
        // parameter for constructor
        // support annotation
        ParameterSpec.Builder paramBuilder = ParameterSpec.builder(type, key);
        if (arg.hasAnnotations()) {
            arg.getAnnotations().forEach(paramBuilder::addAnnotation);
        }
        // nonnull
        if (!type.isPrimitive()) {
            paramBuilder.addAnnotation(ANNOTATION_NONNULL);
        }
        builder.addParameter(paramBuilder.build());

        // statement
        String operationName = arg.getOperationName("put");
        if (arg.hasCustomConverter()) {
            TypeName converter = arg.getConverter();
            builder.addStatement("$T $NConverter = new $T()", converter, key, converter)
                    .addStatement("this.$N.$N($S, $NConverter.convert($N) )",
                            fieldName, operationName, key, key, key);
        } else {
            builder.addStatement("this.$N.$N($S, $N)", fieldName, operationName, key, key);
        }
    }

    return builder.build();
}
 
Example #22
Source Project: soabase-halva   Author: soabase   File: PassCreate.java    License: Apache License 2.0 5 votes vote down vote up
private void addItem(TypeSpec.Builder builder, ImplicitSpec spec, ImplicitItem item)
{
    ExecutableElement method = item.getExecutableElement();
    MethodSpec.Builder methodSpecBuilder = (method.getKind() == ElementKind.CONSTRUCTOR) ? MethodSpec.constructorBuilder() : MethodSpec.methodBuilder(method.getSimpleName().toString());
    methodSpecBuilder.addModifiers(method.getModifiers().stream().filter(m -> m != Modifier.ABSTRACT).collect(Collectors.toList()));
    if ( method.getReturnType().getKind() != TypeKind.VOID )
    {
        methodSpecBuilder.returns(ClassName.get(method.getReturnType()));
    }
    method.getTypeParameters().forEach(typeParameter -> methodSpecBuilder.addTypeVariable(TypeVariableName.get(typeParameter)));

    CodeBlock.Builder codeBlockBuilder = CodeBlock.builder();
    if ( method.getKind() == ElementKind.CONSTRUCTOR )
    {
        codeBlockBuilder.add("super(");
    }
    else if ( method.getReturnType().getKind() == TypeKind.VOID )
    {
        codeBlockBuilder.add("super.$L(", method.getSimpleName());
    }
    else
    {
        codeBlockBuilder.add("return super.$L(", method.getSimpleName());
    }

    CodeBlock methodCode = new ImplicitMethod(environment, method, spec, contextItems).build(parameter -> {
        ParameterSpec.Builder parameterSpec = ParameterSpec.builder(ClassName.get(parameter.asType()), parameter.getSimpleName().toString(), parameter.getModifiers().toArray(new javax.lang.model.element.Modifier[parameter.getModifiers().size()]));
        methodSpecBuilder.addParameter(parameterSpec.build());
    });
    codeBlockBuilder.add(methodCode);
    methodSpecBuilder.addCode(codeBlockBuilder.addStatement(")").build());
    builder.addMethod(methodSpecBuilder.build());
}
 
Example #23
Source Project: pnc   Author: project-ncl   File: PatchDtoGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void createAddMethod(List<MethodSpec> methods, VariableElement dtoField, String patchBuilderClassName) {

        String fieldName = dtoField.getSimpleName().toString();

        String methodName = "add" + StringUtils.firstCharToUpperCase(fieldName);
        MethodSpec.Builder methodBuilder = beginMethod(methodName);
        ParameterSpec parameterSpec = ParameterSpec.builder(ParameterizedTypeName.get(dtoField.asType()), "elements")
                .build();
        methodBuilder.addParameter(parameterSpec);
        methodBuilder.returns(ClassName.get("org.jboss.pnc.client.patch", patchBuilderClassName));
        methodBuilder.addStatement("return add(elements, \"" + fieldName + "\")");

        MethodSpec methodSpec = completeMethod(methodBuilder);
        methods.add(methodSpec);
    }
 
Example #24
Source Project: PreferenceRoom   Author: skydoves   File: PreferenceChangeListenerGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private MethodSpec getOnChangedSpec() {
  return MethodSpec.methodBuilder("onChanged")
      .addParameter(
          ParameterSpec.builder(keyField.typeName, keyField.keyName.toLowerCase()).build())
      .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
      .build();
}
 
Example #25
Source Project: AutoBundle   Author: yatatsu   File: AutoBundleWriter.java    License: Apache License 2.0 5 votes vote down vote up
private static MethodSpec createCallBuilderMethod(AutoBundleBindingClass target) {
    ClassName builderClass = getBuilderClassName(target);
    MethodSpec.Builder builder =
            MethodSpec.methodBuilder("builder")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .addAnnotation(ANNOTATION_NONNULL)
            .returns(builderClass)
            .addCode("return new $T(", builderClass);
    for (int i = 0, count = target.getRequiredArgs().size(); i < count; i++) {
        AutoBundleBindingField arg = target.getRequiredArgs().get(i);
        ParameterSpec.Builder paramBuilder = ParameterSpec.builder(arg.getArgType(),
                arg.getArgKey());
        // annotations
        if (arg.hasAnnotations()) {
            arg.getAnnotations().forEach(paramBuilder::addAnnotation);
        }
        // nonnull
        if (!arg.getArgType().isPrimitive()) {
            paramBuilder.addAnnotation(ANNOTATION_NONNULL);
        }
        // statement
        if (i > 0) {
            builder.addCode(", ");
        }
        builder.addParameter(paramBuilder.build())
                .addCode("$N", arg.getArgKey());
    }
    return builder.addCode(");\n").build();
}
 
Example #26
Source Project: DDComponentForAndroid   Author: luojilab   File: AnnoUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static ParameterSpec generateMethodParameterSpec(TypeMirror typeMirror,
                                                        String paramName) {
    TypeName tn =
            ParameterizedTypeName.get(typeMirror);

    return ParameterSpec.builder(tn, paramName).build();
}
 
Example #27
Source Project: aircon   Author: ironSource   File: TimeConfigProviderGenerator.java    License: MIT License 5 votes vote down vote up
private MethodSpec createDurationPassedPredicate() {
	final MethodSpec.Builder builder = MethodSpec.methodBuilder(getDuringDurationPredicateMethodName())
	                                             .addModifiers(getConfigMethodModifiers())
	                                             .returns(TypeName.BOOLEAN);

	final Set<ParameterSpec> parameterSpecs = getConfigMethodParameters();
	builder.addParameters(parameterSpecs);

	return builder.addCode(getDuringDurationPredicateBodyCodeBlock())
	              .build();
}
 
Example #28
Source Project: client-sdk-java   Author: PlatONnetwork   File: WasmFunctionWrapper.java    License: Apache License 2.0 5 votes vote down vote up
static List<ParameterSpec> buildParameterTypes(List<WasmAbiDefinition.NamedType> namedTypes, Set<String> customTypes) {
	List<ParameterSpec> result = new ArrayList<>(namedTypes.size());
	for (int i = 0; i < namedTypes.size(); i++) {
		WasmAbiDefinition.NamedType namedType = namedTypes.get(i);
		String name = createValidParamName(namedType.getName(), i);
		String type = namedTypes.get(i).getType();
		result.add(ParameterSpec.builder(buildTypeName(type, customTypes), name).build());
	}
	return result;
}
 
Example #29
Source Project: client-sdk-java   Author: PlatONnetwork   File: SolidityFunctionWrapper.java    License: Apache License 2.0 5 votes vote down vote up
static List<ParameterSpec> buildParameterTypes(List<AbiDefinition.NamedType> namedTypes) {
    List<ParameterSpec> result = new ArrayList<>(namedTypes.size());
    for (int i = 0; i < namedTypes.size(); i++) {
        AbiDefinition.NamedType namedType = namedTypes.get(i);

        String name = createValidParamName(namedType.getName(), i);
        String type = namedTypes.get(i).getType();

        result.add(ParameterSpec.builder(buildTypeName(type), name).build());
    }
    return result;
}
 
Example #30
Source Project: etherscan-explorer   Author: bing-chou   File: SolidityFunctionWrapper.java    License: GNU General Public License v3.0 5 votes vote down vote up
String addParameters(
        MethodSpec.Builder methodBuilder, List<AbiDefinition.NamedType> namedTypes) {

    List<ParameterSpec> inputParameterTypes = buildParameterTypes(namedTypes);

    List<ParameterSpec> nativeInputParameterTypes =
            new ArrayList<>(inputParameterTypes.size());
    for (ParameterSpec parameterSpec : inputParameterTypes) {
        TypeName typeName = getWrapperType(parameterSpec.type);
        nativeInputParameterTypes.add(
                ParameterSpec.builder(typeName, parameterSpec.name).build());
    }

    methodBuilder.addParameters(nativeInputParameterTypes);

    if (useNativeJavaTypes) {
        return Collection.join(
                inputParameterTypes,
                ", \n",
                // this results in fully qualified names being generated
                this::createMappedParameterTypes);
    } else {
        return Collection.join(
                inputParameterTypes,
                ", ",
                parameterSpec -> parameterSpec.name);
    }
}