Java 类com.squareup.javapoet.TypeName 实例源码

项目:aws-sdk-java-v2    文件:MemberCopierSpec.java   
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();
}
项目:D-Router    文件:ActivityHelperGenerator.java   
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();
}
项目:auto-value-json    文件:AutoValueJsonExtension.java   
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";
  }
}
项目:PreferenceRoom    文件:PreferenceComponentGenerator.java   
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;
}
项目:json2java4idea    文件:ModelClassBuilder.java   
@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();
}
项目:arez    文件:ComponentDescriptor.java   
/**
 * 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();
}
项目:arez    文件:ComponentDescriptor.java   
@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();
}
项目:Spyglass    文件:TestValueIsAvailableMethodGenerator.java   
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);
}
项目:butterknife-parent    文件:BindingSet.java   
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;
}
项目:RNLearn_Project1    文件:ReactPropertyProcessor.java   
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();
}
项目:json2java4idea    文件:MoshiClassBuilder.java   
@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();
}
项目:aws-sdk-java-v2    文件:SyncClientInterface.java   
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;
}
项目:dataenum    文件:OutputValueFactory.java   
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);
}
项目:Witch-Android    文件:WitchProcessor.java   
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));
    }
}
项目:RxAndroidOrm    文件:ProcessUtils.java   
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;
}
项目:RapidRouter    文件:RouterEntry.java   
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");

    }
}
项目:GeneratorX    文件:CodeGenerator.java   
/**
 * 生成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();
}
项目:aws-sdk-java-v2    文件:MemberCopierSpec.java   
private MethodSpec.Builder copyMethodProto() {
    TypeName parameterType = typeProvider.parameterType(memberModel);
    return MethodSpec.methodBuilder(serviceModelCopiers.copyMethodName())
            .addModifiers(Modifier.STATIC)
            .addParameter(parameterType, memberParamName())
            .returns(typeProvider.fieldType(memberModel));
}
项目:cuckoo    文件:DelegationProcessor.java   
@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());
}
项目:GitHub    文件:FieldCollectionViewBinding.java   
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;
}
项目:GitHub    文件:FieldCollectionViewBinding.java   
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();
}
项目:butterknife-parent    文件:BindingSet.java   
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();
}
项目:aws-sdk-java-v2    文件:AsyncClientInterface.java   
/**
 * 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);
    }
}
项目:json2java4idea    文件:JsonParserImplTest.java   
@Test
public void parseShouldReturnJsonNumberWhenLong() throws Exception {
    // exercise
    final JsonValue value = underTest.parse("4294967296");

    // verify
    assertThat(value)
            .isJsonNumber()
            .hasType(TypeName.LONG)
            .hasValue(4294967296L);
}
项目:jdoocsoup    文件:DataClassBuilderHandler.java   
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());
}
项目:RxAndroidOrm    文件:ProcessUtils.java   
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()));
        }
    }
}
项目:GitHub    文件:ProcessorUtil.java   
/**
 * 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());
}
项目:json2java4idea    文件:JsonNumberTest.java   
@Test
public void getType() throws Exception {
    // exercise
    final TypeName actual = underTest.getType();

    // verify
    assertThat(actual)
            .isEqualTo(TypeName.INT);
}
项目:LifecycleAware    文件:MethodWrapperGenerator.java   
@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();
}
项目:aws-sdk-java-v2    文件:ModelBuilderSpecs.java   
private TypeName builderImplSuperClass() {
    if (isRequest()) {
        return new AwsServiceBaseRequestSpec(intermediateModel).className().nestedClass("BuilderImpl");
    }

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

    return ClassName.OBJECT;
}
项目:ActivityBuilder    文件:ResultModel.java   
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);
}
项目:aws-sdk-java-v2    文件:ListSetters.java   
private MethodSpec fluentEnumVarargToListSetter(TypeName returnType) {
    return fluentSetterBuilder(ParameterSpec.builder(asArrayOfModeledEnum(), fieldName()).build(), returnType)
            .varargs(true)
            .addAnnotation(SafeVarargs.class)
            .addCode(enumVarargToListSetterBody())
            .addStatement("return this")
            .build();
}
项目:remoter    文件:ClassBuilder.java   
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());
}
项目:react4j    文件:Generator.java   
@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;
}
项目:GitHub    文件:ProcessorUtil.java   
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;
}
项目:Stitch    文件:StitchGenerator.java   
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");
}
项目:gwt-jackson-apt    文件:TypeRegistry.java   
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);
    }
}
项目:json2java4idea    文件:JsonValueTest.java   
@Test
public void wrapShouldReturnJsonNumberWhenFloat() throws Exception {
    // exercise
    final JsonValue actual = JsonValue.wrap(10.24f);

    // verify
    assertThat(actual)
            .isJsonNumber()
            .hasType(TypeName.FLOAT)
            .hasValue(10.24f);
}
项目:DDComponentForAndroid    文件:RouterProcessor.java   
/**
 * 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();
}
项目:autoproxy    文件:CommonClassGenerator.java   
@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]);
}