Java Code Examples for com.squareup.javapoet.TypeName

The following are top voted examples for showing how to use com.squareup.javapoet.TypeName. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: aws-sdk-java-v2   File: MemberCopierSpec.java   View source code 6 votes vote down vote up
private MethodSpec builderCopyMethodForList() {
    TypeName keyType = typeProvider.getTypeNameForSimpleType(memberModel.getMapModel().getKeyModel()
                                                                        .getVariable().getVariableType());
    ClassName valueParameter = poetExtensions.getModelClass(memberModel.getMapModel().getValueModel().getC2jShape());
    ClassName builderForParameter = valueParameter.nestedClass("Builder");
    TypeName parameterType =
        ParameterizedTypeName.get(ClassName.get(Map.class), keyType, WildcardTypeName.subtypeOf(builderForParameter));

    CodeBlock code =
        CodeBlock.builder()
                 .beginControlFlow("if ($N == null)", memberParamName())
                 .addStatement("return null")
                 .endControlFlow()
                 .addStatement("return $N($N.entrySet().stream().collect(toMap($T::getKey, e -> e.getValue().build())))",
                               serviceModelCopiers.copyMethodName(),
                               memberParamName(),
                               Map.Entry.class)
                 .build();

    return MethodSpec.methodBuilder(serviceModelCopiers.builderCopyMethodName())
                     .addModifiers(Modifier.STATIC)
                     .addParameter(parameterType, memberParamName())
                     .returns(typeProvider.fieldType(memberModel))
                     .addCode(code)
                     .build();
}
 
Example 2
Project: D-Router   File: ActivityHelperGenerator.java   View source code 6 votes vote down vote up
private String getMethodByType(TypeName clazz) {
    StringBuilder sb = new StringBuilder("get");
    if (clazz.equals(TypeName.INT) || clazz.equals(TypeName.INT.box())) {
        sb.append("Int");
    } else if (clazz.equals(TypeName.BOOLEAN) || clazz.equals(TypeName.BOOLEAN.box())) {
        sb.append("Boolean");
    } else if (clazz.equals(TypeName.FLOAT) || clazz.equals(TypeName.FLOAT.box())) {
        sb.append("Float");
    } else if (clazz.equals(TypeName.DOUBLE) || clazz.equals(TypeName.DOUBLE.box())) {
        sb.append("Double");
    } else if (clazz.equals(TypeName.LONG) || clazz.equals(TypeName.LONG.box())) {
        sb.append("Long");
    } else if (clazz.equals(TypeName.SHORT) || clazz.equals(TypeName.SHORT.box())) {
        sb.append("Short");
    } else if (clazz.equals(TypeName.CHAR) || clazz.equals(TypeName.CHAR.box())) {
        sb.append("Char");
    } else if (clazz.equals(TypeName.VOID) || clazz.equals(TypeName.VOID.box()) ||
            clazz.equals(TypeName.BYTE) || clazz.equals(TypeName.BYTE.box())
            || clazz.equals(TypeName.OBJECT)) {
        //should not use this type
    } else {
        sb.append("String");
    }
    return sb.append("Param").toString();
}
 
Example 3
Project: auto-value-json   File: AutoValueJsonExtension.java   View source code 6 votes vote down vote up
private String defaultValue(JsonProperty property, TypeName type) {
  if (property.defaultValue != null) {
    return property.defaultValue;
  }
  if (type == TypeName.BOOLEAN) {
    return "false";
  } else if (type == TypeName.BYTE) {
    return "(byte) 0";
  } else if (type == TypeName.SHORT) {
    return "0";
  } else if (type == TypeName.INT) {
    return "0";
  } else if (type == TypeName.LONG) {
    return "0L";
  } else if (type == TypeName.CHAR) {
    return "'\0'";
  } else if (type == TypeName.FLOAT) {
    return "0.0f";
  } else if (type == TypeName.DOUBLE) {
    return "0.0d";
  } else {
    return "null";
  }
}
 
Example 4
Project: PreferenceRoom   File: PreferenceComponentGenerator.java   View source code 6 votes vote down vote up
private List<MethodSpec> getSuperMethodSpecs() {
    List<MethodSpec> methodSpecs = new ArrayList<>();
    this.annotatedClazz.annotatedElement.getEnclosedElements().stream()
            .filter(element -> element instanceof ExecutableElement)
            .map(element -> (ExecutableElement) element)
            .forEach(method -> {
                ClassName preferenceRoom = ClassName.get(PreferenceRoom.class);
                MethodSpec.Builder builder = MethodSpec.overriding(method);
                MethodSpec methodSpec = builder.addStatement("$T.inject($N)", preferenceRoom, method.getParameters().get(0).getSimpleName()).build();
                if(methodSpec.returnType != TypeName.get(Void.TYPE)) {
                    throw new VerifyException(String.format("Returned '%s'. only return type can be void.", methodSpec.returnType.toString()));
                }
                methodSpecs.add(methodSpec);
            });
    return methodSpecs;
}
 
Example 5
Project: json2java4idea   File: ModelClassBuilder.java   View source code 6 votes vote down vote up
@Nonnull
@Override
protected List<MethodSpec> buildMethods() {
    final MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC);

    final ImmutableList.Builder<MethodSpec> builder = ImmutableList.builder();
    getProperties().entrySet().forEach(property -> {
        final String name = property.getKey();
        final TypeName type = property.getValue();
        final String fieldName = fieldNamePolicy.convert(name, type);
        final String methodName = methodNamePolicy.convert(name, type);
        builder.add(MethodSpec.methodBuilder(methodName)
                .addModifiers(Modifier.PUBLIC)
                .returns(type)
                .addStatement("return $L", fieldName)
                .build());

        final String propertyName = parameterNamePolicy.convert(name, type);
        constructorBuilder.addParameter(ParameterSpec.builder(type, propertyName)
                .build())
                .addStatement("this.$L = $L", fieldName, propertyName);
    });
    builder.add(constructorBuilder.build());
    return builder.build();
}
 
Example 6
Project: arez   File: ComponentDescriptor.java   View source code 6 votes vote down vote up
/**
 * Generate the isDisposed method.
 */
@Nonnull
private MethodSpec buildIsDisposed()
  throws ArezProcessorException
{
  final MethodSpec.Builder builder =
    MethodSpec.methodBuilder( "isDisposed" ).
      addModifiers( Modifier.PUBLIC ).
      addAnnotation( Override.class ).
      returns( TypeName.BOOLEAN );

  final CodeBlock.Builder block = CodeBlock.builder();
  block.beginControlFlow( "if ( $N().isTransactionActive() && !this.$N.isDisposed() ) ",
                          getContextMethodName(),
                          GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME );
  block.addStatement( "this.$N.reportObserved()", GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME );
  block.addStatement( "return this.$N", GeneratorUtil.DISPOSED_FIELD_NAME );
  block.nextControlFlow( "else" );
  block.addStatement( "return this.$N", GeneratorUtil.DISPOSED_FIELD_NAME );
  block.endControlFlow();
  builder.addCode( block.build() );

  return builder.build();
}
 
Example 7
Project: arez   File: ComponentDescriptor.java   View source code 6 votes vote down vote up
@Nullable
private MethodSpec buildComponentTypeNameMethod()
  throws ArezProcessorException
{
  if ( null == _componentTypeName )
  {
    return null;
  }

  final MethodSpec.Builder builder =
    MethodSpec.methodBuilder( _componentTypeName.getSimpleName().toString() );
  ProcessorUtil.copyAccessModifiers( _componentTypeName, builder );
  builder.addModifiers( Modifier.FINAL );
  builder.addAnnotation( GeneratorUtil.NONNULL_CLASSNAME );

  builder.returns( TypeName.get( String.class ) );
  builder.addStatement( "return $S", _type );
  return builder.build();
}
 
Example 8
Project: Spyglass   File: TestValueIsAvailableMethodGenerator.java   View source code 6 votes vote down vote up
private void checkCompiles(final MethodSpec method) {
	final TypeSpec wrapperTypeSpec = CallerDef
			.getNewCallerSubclassPrototype("Wrapper", TypeName.OBJECT)
			.addMethod(CallerDef.getNewCallMethodPrototype().build())
			.addMethod(CallerDef.getNewConstructorPrototype(TypeName.OBJECT).build())
			.addMethod(method)
			.build();

	final JavaFile wrapperJavaFile = JavaFile
			.builder("", wrapperTypeSpec)
			.build();

	final Set<JavaFile> filesToCompile = new HashSet<>();
	filesToCompile.add(wrapperJavaFile);
	filesToCompile.add(CallerDef.SRC_FILE);

	CompileChecker.checkCompiles(filesToCompile);
}
 
Example 9
Project: butterknife-parent   File: BindingSet.java   View source code 6 votes vote down vote up
private BindingSet(TypeName targetTypeName, ClassName bindingClassName, boolean isFinal,
                   boolean isView, boolean isActivity,boolean isFragment, boolean isDialog, ImmutableList<ViewBinding> viewBindings,
                   ImmutableList<FieldCollectionViewBinding> collectionBindings,
                   ImmutableList<ResourceBinding> resourceBindings, BindingSet parentBinding, @LayoutRes int layoutId) {
    this.isFinal = isFinal;
    this.targetTypeName = targetTypeName;
    this.bindingClassName = bindingClassName;
    this.isView = isView;
    this.isActivity = isActivity;
    this.isFragment = isFragment;
    this.isDialog = isDialog;
    this.viewBindings = viewBindings;
    this.collectionBindings = collectionBindings;
    this.resourceBindings = resourceBindings;
    this.parentBinding = parentBinding;
    this.layoutId = layoutId;
}
 
Example 10
Project: RNLearn_Project1   File: ReactPropertyProcessor.java   View source code 6 votes vote down vote up
private static MethodSpec generateSetPropertySpec(
    ClassInfo classInfo,
    List<PropertyInfo> properties) {
  MethodSpec.Builder builder = MethodSpec.methodBuilder("setProperty")
      .addModifiers(PUBLIC)
      .addAnnotation(Override.class)
      .returns(TypeName.VOID);

  switch (classInfo.getType()) {
    case VIEW_MANAGER:
      builder
          .addParameter(classInfo.mClassName, "manager")
          .addParameter(classInfo.mViewType, "view");
      break;
    case SHADOW_NODE:
      builder
          .addParameter(classInfo.mClassName, "node");
      break;
  }

  return builder
      .addParameter(STRING_TYPE, "name")
      .addParameter(PROPS_TYPE, "props")
      .addCode(generateSetProperty(classInfo, properties))
      .build();
}
 
Example 11
Project: json2java4idea   File: MoshiClassBuilder.java   View source code 6 votes vote down vote up
@Nonnull
@Override
protected List<MethodSpec> buildMethods() {
    final MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC);

    final ImmutableList.Builder<MethodSpec> builder = ImmutableList.builder();
    getProperties().entrySet().forEach(property -> {
        final String name = property.getKey();
        final TypeName type = property.getValue();
        final String fieldName = fieldNamePolicy.convert(name, type);
        final String methodName = methodNamePolicy.convert(name, type);
        builder.add(MethodSpec.methodBuilder(methodName)
                .addModifiers(Modifier.PUBLIC)
                .returns(type)
                .addStatement("return $L", fieldName)
                .build());

        final String propertyName = parameterNamePolicy.convert(name, type);
        constructorBuilder.addParameter(ParameterSpec.builder(type, propertyName)
                .build())
                .addStatement("this.$L = $L", fieldName, propertyName);
    });
    builder.add(constructorBuilder.build());
    return builder.build();
}
 
Example 12
Project: aws-sdk-java-v2   File: SyncClientInterface.java   View source code 6 votes vote down vote up
private List<MethodSpec> streamingSimpleMethods(OperationModel opModel) {
    TypeName responseType = ClassName.get(model.getMetadata().getFullModelPackageName(),
                                          opModel.getReturnType().getReturnType());
    ClassName requestType = ClassName.get(model.getMetadata().getFullModelPackageName(),
                                          opModel.getInput().getVariableType());
    List<MethodSpec> simpleMethods = new ArrayList<>();
    if (opModel.hasStreamingInput()) {
        simpleMethods.add(uploadFromFileSimpleMethod(opModel, responseType, requestType));
    }
    if (opModel.hasStreamingOutput()) {
        simpleMethods.add(downloadToFileSimpleMethod(opModel, responseType, requestType));
        simpleMethods.add(inputStreamSimpleMethod(opModel, responseType, requestType));
        simpleMethods.add(bytesSimpleMethod(opModel, responseType, requestType));
    }
    return simpleMethods;
}
 
Example 13
Project: dataenum   File: OutputValueFactory.java   View source code 6 votes vote down vote up
static OutputValue create(Value value, ClassName specOutputClass, Spec spec)
    throws ParserException {
  ClassName outputClass = specOutputClass.nestedClass(value.name());
  Iterable<TypeVariableName> typeVariables = getTypeVariables(value, spec.typeVariables());

  List<Parameter> parameters = new ArrayList<>();
  for (Parameter parameter : value.parameters()) {
    TypeName rawParamType = withoutTypeParameters(parameter.type());

    if (isDataEnumParameter(rawParamType)) {
      TypeName paramOutputType =
          withParametersFromOther(toOutputClass(rawParamType), parameter.type());
      parameters.add(new Parameter(parameter.name(), paramOutputType, parameter.canBeNull()));
    } else {
      parameters.add(parameter);
    }
  }

  return new OutputValue(outputClass, value.name(), parameters, typeVariables);
}
 
Example 14
Project: Witch-Android   File: WitchProcessor.java   View source code 6 votes vote down vote up
private void addOnBind(Element targetMember, TypeMirror bindTypeMirror, HashMap<Element, List<ViewBinder.Builder>> targetViewBinders) {
    boolean match = false;

    TypeName typeName = TypeName.get(bindTypeMirror);
    DeclaredType bindingDeclaredType = typeUtils.types().getDeclaredType(elementUtils.getTypeElement(bindTypeMirror.toString()));
    OnBind onBind = new NewInstance(typeName);

    // OnBind
    TypeMirror onBindTypeMirror = typeUtils.onBindDeclaredType();
    if (typeUtils.types().isSubtype(bindingDeclaredType, onBindTypeMirror)) {
        addOnBind(targetMember, onBind, targetViewBinders);
        match = true;
    }

    if (!match) {
        String stringBuilder = String.valueOf(typeName) +
                " does not implement required interface. Make sure classes provided in: " +
                "@" + SupportedAnnotations.OnBind.name + " or " +
                "@" + SupportedAnnotations.OnBindEach.name +
                " implements one or more of the following: " +
                TypeUtils.ON_BIND;

        throw new WitchException(logger.logError(stringBuilder));
    }
}
 
Example 15
Project: RxAndroidOrm   File: ProcessUtils.java   View source code 6 votes vote down vote up
public static TypeName getUnboxedClass(Element element) {
    TypeName typeName = getFieldClass(element);
    if (TypeName.INT.equals(typeName)) {
        return TypeName.get(Integer.class);
    }
    if (TypeName.LONG.equals(typeName)) {
        return TypeName.get(Long.class);
    }
    if (TypeName.FLOAT.equals(typeName)) {
        return TypeName.get(Float.class);
    }
    if (TypeName.DOUBLE.equals(typeName)) {
        return TypeName.get(Double.class);
    }
    if (TypeName.BOOLEAN.equals(typeName)) {
        return TypeName.get(Boolean.class);
    }
    if (TypeName.get(String.class).equals(typeName)) {
        return typeName;
    }
    return null;
}
 
Example 16
Project: RapidRouter   File: RouterEntry.java   View source code 6 votes vote down vote up
private void onRegularMapperMethodStatement(ClassName hashMapClassName, TypeName routerTargetTypeName, MethodSpec.Builder calcRegMapperMethodBuilder, UriEntry uriEntry) {
    calcRegMapperMethodBuilder.addCode("// " + uriEntry.getRouterTargetClass() + "\n");

    List<ParamEntry> paramEntries = uriEntry.getParams();
    int paramSize = null == paramEntries ? 0 : paramEntries.size();
    if (paramSize <= 0) {
        calcRegMapperMethodBuilder.addStatement(
                "$L.put($S, new $T($T.class, null))",
                "routerMapper", uriEntry.getUriRegular(), routerTargetTypeName, ClassName.get(uriEntry.getRouterTargetClass().asType()));
    } else {
        calcRegMapperMethodBuilder.addStatement("$L = new $T<>(" + paramSize + ", 1F)",
                "params", hashMapClassName);
        for (ParamEntry paramEntry : paramEntries) {
            LogUtil.logger("[Reg]paramEntry: " + paramEntry);
            calcRegMapperMethodBuilder.addStatement("params.put($S, $T.class)", paramEntry.getName(), paramEntry.getType());
        }

        calcRegMapperMethodBuilder.addStatement(
                "$L.put($S, new $T($T.class, $L))",
                "routerMapper", uriEntry.getUriRegular(), routerTargetTypeName, ClassName.get(uriEntry.getRouterTargetClass().asType()), "params");

    }
}
 
Example 17
Project: GeneratorX   File: CodeGenerator.java   View source code 6 votes vote down vote up
/**
 * 生成set方法
 * @param variable
 * @return String getS(String s)
 */
protected MethodSpec makeSetMethod(String variable) {

    //方法内的几行code this.variable = var;
    StringBuilder builder = new StringBuilder();
    builder.append(String.format("this.%s", variable));
    builder.append(" = " + variable);

    //方法的 头 和 尾
    return methodBuilder(
            "set" + com.androidyuan.Helper.ClsHelper.bigFirstString(variable)).addModifiers(
            PUBLIC).returns(
            TypeName.VOID)//public void setField
            .addParameter(getFiledType(variable), variable)//(String variableNames)
            .addStatement(builder.toString())// 添加方法内的几行代码到这里
            .build();
}
 
Example 18
Project: aws-sdk-java-v2   File: MemberCopierSpec.java   View source code 5 votes vote down vote up
private MethodSpec.Builder copyMethodProto() {
    TypeName parameterType = typeProvider.parameterType(memberModel);
    return MethodSpec.methodBuilder(serviceModelCopiers.copyMethodName())
            .addModifiers(Modifier.STATIC)
            .addParameter(parameterType, memberParamName())
            .returns(typeProvider.fieldType(memberModel));
}
 
Example 19
Project: cuckoo   File: DelegationProcessor.java   View source code 5 votes vote down vote up
@TargetApi(24)
private List<MethodSpec> getConstructorSpecs(List<ExecutableElement> constructorElements, TypeElement originalClass) {
    return constructorElements.stream()
            .map(constructor -> {
                List<String> parameterNames = constructor.getParameters()
                        .stream()
                        .map(parameter -> parameter.getSimpleName().toString())
                        .collect(Collectors.toList());

                List<ParameterSpec> parameters = constructor.getParameters()
                        .stream()
                        .map(ParameterSpec::get)
                        .collect(Collectors.toList());

                MethodSpec.Builder constructorBuilder = MethodSpec
                        .constructorBuilder()
                        .addModifiers(Modifier.PRIVATE)
                        .addParameters(parameters)
                        .addStatement("super($L)", String.join(",", parameterNames));

                MethodSpec.Builder initializerBuilder = MethodSpec
                        .methodBuilder("newInstance")
                        .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                        .returns(TypeName.get(originalClass.asType()))
                        .addParameters(parameters)
                        .addStatement("return new $L($L)", getSubclassName(originalClass), String.join(",", parameterNames));

                return Arrays.asList(constructorBuilder.build(), initializerBuilder.build());
            })
            .flatMap(Collection::stream)
            .collect(Collectors.toList());
}
 
Example 20
Project: GitHub   File: FieldCollectionViewBinding.java   View source code 5 votes vote down vote up
FieldCollectionViewBinding(String name, TypeName type, Kind kind, List<Id> ids,
    boolean required) {
  this.name = name;
  this.type = type;
  this.kind = kind;
  this.ids = ids;
  this.required = required;
}
 
Example 21
Project: GitHub   File: FieldCollectionViewBinding.java   View source code 5 votes vote down vote up
CodeBlock render() {
  CodeBlock.Builder builder = CodeBlock.builder()
      .add("target.$L = $T.$L(", name, UTILS, kind.factoryName);
  for (int i = 0; i < ids.size(); i++) {
    if (i > 0) {
      builder.add(", ");
    }
    builder.add("\n");

    boolean requiresCast = requiresCast(type);
    if (!requiresCast && !required) {
      builder.add("source.findViewById($L)", ids.get(i).code);
    } else {
      builder.add("$T.find", UTILS);
      builder.add(required ? "RequiredView" : "OptionalView");
      if (requiresCast) {
        builder.add("AsType");
      }
      builder.add("(source, $L, \"field '$L'\"", ids.get(i).code, name);
      if (requiresCast) {
        TypeName rawType = type;
        if (rawType instanceof ParameterizedTypeName) {
          rawType = ((ParameterizedTypeName) rawType).rawType;
        }
        builder.add(", $T.class", rawType);
      }
      builder.add(")");
    }
  }
  return builder.add(")").build();
}
 
Example 22
Project: butterknife-parent   File: BindingSet.java   View source code 5 votes vote down vote up
private MethodSpec createGetLayoutMethod() {
    MethodSpec.Builder result = MethodSpec.methodBuilder("getLayout")
            .returns(TypeName.OBJECT)
            .addAnnotation(Override.class)
            .addModifiers(PUBLIC);
    if (!isActivity) {
        result.addStatement("return source");
    } else {
        result.addStatement("throw new $T($S)", IllegalStateException.class,
                "sorry,you can't call this way");
    }
    return result.build();
}
 
Example 23
Project: aws-sdk-java-v2   File: AsyncClientInterface.java   View source code 5 votes vote down vote up
/**
 * Get the return {@link TypeName} of an async method. Depends on whether it's streaming or not.
 *
 * @param opModel          Operation to get return type for.
 * @param responsePojoType Type of Response POJO.
 * @return Return type of the operation method.
 */
private TypeName getAsyncReturnType(OperationModel opModel, ClassName responsePojoType) {
    if (opModel.hasStreamingOutput()) {
        return completableFutureType(STREAMING_TYPE_VARIABLE);
    } else {
        return completableFutureType(responsePojoType);
    }
}
 
Example 24
Project: json2java4idea   File: JsonParserImplTest.java   View source code 5 votes vote down vote up
@Test
public void parseShouldReturnJsonNumberWhenLong() throws Exception {
    // exercise
    final JsonValue value = underTest.parse("4294967296");

    // verify
    assertThat(value)
            .isJsonNumber()
            .hasType(TypeName.LONG)
            .hasValue(4294967296L);
}
 
Example 25
Project: jdoocsoup   File: DataClassBuilderHandler.java   View source code 5 votes vote down vote up
private void parseDataFromDescriptor() {
    if (descriptor.getElementKind() == ElementKind.CLASS) {
        for (VariableElement var : descriptor.getFields()) {

            if (checkIfFieldForProcessing(var)) {
                continue;
            }

            DataClassBuilder.MethodDocs builderMethodDocsAnnotation = var.getAnnotation(DataClassBuilder.MethodDocs.class);
            DataClassBuilder.HasDefault hasDefaultAnnotation = var.getAnnotation(DataClassBuilder.HasDefault.class);

            FieldSpec.Builder fieldSpec = FieldSpec.builder(TypeName.get(var.asType()), var.getSimpleName().toString()).addModifiers(Modifier.PRIVATE);

            if (hasDefaultAnnotation != null) {
                fieldSpec.initializer(CodeBlock.of("$L", hasDefaultAnnotation.value()));
            }

            MethodSpec.Builder methodSpec = MethodSpec.methodBuilder(var.getSimpleName().toString()).addModifiers(Modifier.PUBLIC)
                    .addParameter(ParameterSpec.builder(TypeName.get(var.asType()), var.getSimpleName().toString()).build())
                    .addStatement("this.$N = $N", var.getSimpleName(), var.getSimpleName())
                    .addStatement("return this")
                    .returns(ClassName.get(descriptor.getPackageName(), descriptor.getDataClassBuilderName()));

            if (builderMethodDocsAnnotation != null) {
                methodSpec.addJavadoc(builderMethodDocsAnnotation.value() + "\n");
            }

            builderClassSpecBuilder.addField(fieldSpec.build());
            builderClassSpecBuilder.addMethod(methodSpec.build());
        }
    }

    builderClassSpecBuilder.addMethod(createBuilderMethodSpec());
    builderClassSpecBuilder.addMethod(createBuildMethodSpec());
    builderClassSpecBuilder.addMethod(createPrivateConstructor());
}
 
Example 26
Project: RxAndroidOrm   File: ProcessUtils.java   View source code 5 votes vote down vote up
public static TypeName getFieldClass(Element element) {
    if (isArray(element)) {
        TypeName typeName = getArrayEnclosedType(element);
        return unbox(typeName);
    } else {
        TypeName enclosed = unbox(getEnclosedTypeName(element));
        if (enclosed != null) {
            return enclosed;
        } else {
            return unbox(TypeName.get(element.asType()));
        }
    }
}
 
Example 27
Project: GitHub   File: ProcessorUtil.java   View source code 5 votes vote down vote up
/**
 * Returns a safe String to use in a Javadoc that will function in a link.
 *
 * <p>This method exists because by Javadoc doesn't handle type parameters({@literal <T>}
 * in {@literal RequestOptions<T>} for example).
 */
private TypeName getJavadocSafeName(Element element) {
  Types typeUtils = processingEnv.getTypeUtils();
  TypeMirror type = element.asType();
  if (typeUtils.asElement(type) == null) {
    // If there is no Element, it's a primitive and can't have additional types, so we're done.
    return ClassName.get(element.asType());
  }
  Name simpleName = typeUtils.asElement(type).getSimpleName();
  return ClassName.bestGuess(simpleName.toString());
}
 
Example 28
Project: json2java4idea   File: JsonNumberTest.java   View source code 5 votes vote down vote up
@Test
public void getType() throws Exception {
    // exercise
    final TypeName actual = underTest.getType();

    // verify
    assertThat(actual)
            .isEqualTo(TypeName.INT);
}
 
Example 29
Project: LifecycleAware   File: MethodWrapperGenerator.java   View source code 5 votes vote down vote up
@Override
public MethodSpec defineConstructor() {
    return MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addParameter(TypeName.get(annotatedElement.asType()), FIELD_NAME)
            .addStatement("this.$L = $L", FIELD_NAME, FIELD_NAME)
            .build();
}
 
Example 30
Project: aws-sdk-java-v2   File: ModelBuilderSpecs.java   View source code 5 votes vote down vote up
private TypeName builderImplSuperClass() {
    if (isRequest()) {
        return new AwsServiceBaseRequestSpec(intermediateModel).className().nestedClass("BuilderImpl");
    }

    if (isResponse()) {
        return new AwsServiceBaseResponseSpec(intermediateModel).className().nestedClass("BuilderImpl");
    }

    return ClassName.OBJECT;
}
 
Example 31
Project: ActivityBuilder   File: ResultModel.java   View source code 5 votes vote down vote up
public TypeName getConsumerTypeWithContext() throws IOException {
  int count = getParameters().size() + 1;
  TypeName[] types = new TypeName[count];
  types[0] = TypeVariableName.get("A");
  for (int i = 1; i < count; i++) {
    types[i] = TypeName.get(getParameters().get(i - 1).getObjectType());
  }
  return ParameterizedTypeName
      .get(ConsumerHelper.get(count), types);
}
 
Example 32
Project: aws-sdk-java-v2   File: ListSetters.java   View source code 5 votes vote down vote up
private MethodSpec fluentEnumVarargToListSetter(TypeName returnType) {
    return fluentSetterBuilder(ParameterSpec.builder(asArrayOfModeledEnum(), fieldName()).build(), returnType)
            .varargs(true)
            .addAnnotation(SafeVarargs.class)
            .addCode(enumVarargToListSetterBody())
            .addStatement("return this")
            .build();
}
 
Example 33
Project: remoter   File: ClassBuilder.java   View source code 5 votes vote down vote up
public JavaFile.Builder buildStubClass() {
    ClassName stubClassName = getStubClassName();

    TypeSpec.Builder stubClassBuilder = TypeSpec
            .classBuilder(stubClassName.simpleName())
            .addModifiers(Modifier.PUBLIC)
            .superclass(TypeName.get(getBindingManager().getType("android.os.Binder")));

    for (TypeParameterElement typeParameterElement : ((TypeElement) getRemoterInterfaceElement()).getTypeParameters()) {
        stubClassBuilder.addTypeVariable(TypeVariableName.get(typeParameterElement.toString()));
    }


    //constructor
    stubClassBuilder.addMethod(MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addJavadoc("Initialize this {@link " + getStubClassName().simpleName() + "} with the given {@link " + getRemoterInterfaceClassName() + "} implementation \n\n")
            .addJavadoc("@param serviceImpl An implementation of {@link " + getRemoterInterfaceClassName() + "}\n")
            .addParameter(TypeName.get(getRemoterInterfaceElement().asType()), "serviceImpl")
            .addStatement("this.serviceImpl = serviceImpl")
            .beginControlFlow("this.attachInterface(new $T()", ClassName.get("android.os", "IInterface"))
            .beginControlFlow("public $T asBinder()", ClassName.get("android.os", "IBinder"))
            .addStatement("return " + stubClassName.simpleName() + ".this")
            .endControlFlow()
            .endControlFlow()
            .addStatement(", DESCRIPTOR)")
            .build());


    getBindingManager().getFieldBuilder(getRemoterInterfaceElement()).addStubFields(stubClassBuilder);
    getBindingManager().getMethoddBuilder(getRemoterInterfaceElement()).addStubMethods(stubClassBuilder);

    stubClassBuilder.addJavadoc("Wraps a {@link " + getRemoterInterfaceClassName() + "} implementation and expose it as a remote {@link IBinder}\n");
    stubClassBuilder.addJavadoc("<p>\n");
    stubClassBuilder.addJavadoc("Autogenerated by <a href=\"https://bit.ly/Remoter\">Remoter</a>\n");
    stubClassBuilder.addJavadoc("@see " + getProxyClassName().simpleName() + "\n");

    return JavaFile.builder(stubClassName.packageName(), stubClassBuilder.build());
}
 
Example 34
Project: react4j   File: Generator.java   View source code 5 votes vote down vote up
@Nonnull
private static MethodSpec.Builder buildEventHandlerActionMethod( @Nonnull final EventHandlerDescriptor eventHandler )
{
  final MethodSpec.Builder method =
    MethodSpec.methodBuilder( eventHandler.getMethod().getSimpleName().toString() ).
      returns( TypeName.get( eventHandler.getMethodType().getReturnType() ) );
  ProcessorUtil.copyTypeParameters( eventHandler.getMethodType(), method );
  ProcessorUtil.copyAccessModifiers( eventHandler.getMethod(), method );
  ProcessorUtil.copyDocumentedAnnotations( eventHandler.getMethod(), method );

  final AnnotationSpec.Builder annotation =
    AnnotationSpec.builder( ACTION_CLASSNAME ).
      addMember( "reportParameters", "false" );
  method.addAnnotation( annotation.build() );

  final int paramCount = eventHandler.getMethod().getParameters().size();
  for ( int i = 0; i < paramCount; i++ )
  {
    final TypeMirror paramType = eventHandler.getMethodType().getParameterTypes().get( i );
    final ParameterSpec.Builder parameter =
      ParameterSpec.builder( TypeName.get( paramType ), "arg" + i, Modifier.FINAL );
    ProcessorUtil.copyDocumentedAnnotations( eventHandler.getMethod().getParameters().get( i ), parameter );
    method.addParameter( parameter.build() );
  }
  final String params =
    0 == paramCount ?
    "" :
    IntStream.range( 0, paramCount ).mapToObj( i -> "arg" + i ).collect( Collectors.joining( "," ) );

  final boolean isVoid = eventHandler.getMethodType().getReturnType().getKind() == TypeKind.VOID;

  method.addStatement( ( isVoid ? "" : "return " ) + "super.$N(" + params + ")",
                       eventHandler.getMethod().getSimpleName() );
  return method;
}
 
Example 35
Project: GitHub   File: ProcessorUtil.java   View source code 5 votes vote down vote up
static MethodSpec.Builder overriding(ExecutableElement method) {
  String methodName = method.getSimpleName().toString();

  MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName)
      .addAnnotation(Override.class);

  Set<Modifier> modifiers = method.getModifiers();
  modifiers = new LinkedHashSet<>(modifiers);
  modifiers.remove(Modifier.ABSTRACT);
  Modifier defaultModifier = null;
  // Modifier.DEFAULT doesn't exist until Java 8.
  try {
    defaultModifier = Modifier.valueOf("DEFAULT");
  } catch (IllegalArgumentException e) {
    // Ignored.
  }
  modifiers.remove(defaultModifier);

  builder = builder.addModifiers(modifiers);

  for (TypeParameterElement typeParameterElement : method.getTypeParameters()) {
    TypeVariable var = (TypeVariable) typeParameterElement.asType();
    builder = builder.addTypeVariable(TypeVariableName.get(var));
  }

  builder = builder.returns(TypeName.get(method.getReturnType()))
      .addParameters(getParameters(method))
      .varargs(method.isVarArgs());

  for (TypeMirror thrownType : method.getThrownTypes()) {
    builder = builder.addException(TypeName.get(thrownType));
  }

  return builder;
}
 
Example 36
Project: Stitch   File: StitchGenerator.java   View source code 5 votes vote down vote up
private StitchGenerator(TypeName targetTypeName, ClassName generatingClassName,
        ImmutableList<MethodThreadStitching> methodThreadStitchings) {

    this.mTargetTypeName = targetTypeName;
    this.mGeneratingClassName = generatingClassName;
    this.mMethodThreadStitchings = methodThreadStitchings;
    mNewThreadExecutor = ClassName.get("amitkma.stitchlib.executors", "NewThreadExecutor");
    mUiExecutor = ClassName.get("amitkma.stitchlib.executors", "UiExecutor");
    mBackgroundExecutor = ClassName.get("amitkma.stitchlib.executors", "BackgroundExecutor");
}
 
Example 37
Project: gwt-jackson-apt   File: TypeRegistry.java   View source code 5 votes vote down vote up
public static void registerSerializer(String type, TypeName serializer) {
    if (customMappers.containsKey(type)) {
        customMappers.get(type).serializer = serializer;
    } else {
        ClassMapper classMapper = new ClassMapper(type);
        classMapper.serializer = serializer;
        customMappers.put(type, classMapper);
    }
}
 
Example 38
Project: json2java4idea   File: JsonValueTest.java   View source code 5 votes vote down vote up
@Test
public void wrapShouldReturnJsonNumberWhenFloat() throws Exception {
    // exercise
    final JsonValue actual = JsonValue.wrap(10.24f);

    // verify
    assertThat(actual)
            .isJsonNumber()
            .hasType(TypeName.FLOAT)
            .hasValue(10.24f);
}
 
Example 39
Project: DDComponentForAndroid   File: RouterProcessor.java   View source code 5 votes vote down vote up
/**
 * create init map method
 */
private MethodSpec generateInitMapMethod() {
    TypeName returnType = TypeName.VOID;

    MethodSpec.Builder openUriMethodSpecBuilder = MethodSpec.methodBuilder("initMap")
            .returns(returnType)
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC);

    openUriMethodSpecBuilder.addStatement("super.initMap()");

    for (Node node : routerNodes) {
        openUriMethodSpecBuilder.addStatement(
                mRouteMapperFieldName + ".put($S,$T.class)",
                node.getPath(),
                ClassName.get((TypeElement) node.getRawType()));

        // Make map body for paramsType
        StringBuilder mapBodyBuilder = new StringBuilder();
        Map<String, Integer> paramsType = node.getParamsType();
        if (MapUtils.isNotEmpty(paramsType)) {
            for (Map.Entry<String, Integer> types : paramsType.entrySet()) {
                mapBodyBuilder.append("put(\"").append(types.getKey()).append("\", ").append(types.getValue()).append("); ");
            }
        }
        String mapBody = mapBodyBuilder.toString();
        logger.info(">>> mapBody: " + mapBody + " <<<");
        if (!StringUtils.isEmpty(mapBody)) {
            openUriMethodSpecBuilder.addStatement(
                    mParamsMapperFieldName + ".put($T.class,"
                            + "new java.util.HashMap<String, Integer>(){{" + mapBody + "}}" + ")",
                    ClassName.get((TypeElement) node.getRawType()));
        }
    }

    return openUriMethodSpecBuilder.build();
}
 
Example 40
Project: autoproxy   File: CommonClassGenerator.java   View source code 5 votes vote down vote up
@NonNull
protected FieldSpec[] createMembers() {
    final List<FieldSpec> fields = new ArrayList<>();

    final TypeName typeOfField = TypeName.get(type.element.asType());
    final FieldSpec.Builder builder = FieldSpec.builder(typeOfField, "inner", Modifier.PROTECTED, Modifier.FINAL);
    fields.add(builder.build());

    return fields.toArray(new FieldSpec[0]);
}