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

项目:GitHub    文件:RequestManagerGenerator.java   
private MethodSpec generateAdditionalRequestManagerMethod(ExecutableElement extensionMethod) {
  String returnType = processorUtil.findClassValuesFromAnnotationOnClassAsNames(extensionMethod,
      GlideType.class).iterator().next();
  ClassName returnTypeClassName = ClassName.bestGuess(returnType);
  ParameterizedTypeName parameterizedTypeName =
      ParameterizedTypeName.get(generatedRequestBuilderClassName, returnTypeClassName);

  return MethodSpec.methodBuilder(extensionMethod.getSimpleName().toString())
      .addModifiers(Modifier.PUBLIC)
      .returns(parameterizedTypeName)
      .addJavadoc(processorUtil.generateSeeMethodJavadoc(extensionMethod))
      .addStatement(
          "$T requestBuilder = this.as($T.class)", parameterizedTypeName, returnTypeClassName)
      .addStatement("$T.$N(requestBuilder)",
          extensionMethod.getEnclosingElement(), extensionMethod.getSimpleName())
      .addStatement("return requestBuilder")
      .build();
}
项目:GitHub    文件:RequestBuilderGenerator.java   
private List<MethodSpec> generateConstructors() {
  ParameterizedTypeName classOfTranscodeType =
      ParameterizedTypeName.get(ClassName.get(Class.class), transcodeTypeName);

  TypeName wildcardOfObject = WildcardTypeName.subtypeOf(Object.class);
  ParameterizedTypeName requestBuilderOfWildcardOfObject =
      ParameterizedTypeName.get(ClassName.get(requestBuilderType), wildcardOfObject);

  MethodSpec firstConstructor =
      MethodSpec.constructorBuilder()
          .addParameter(classOfTranscodeType, "transcodeClass")
          .addParameter(requestBuilderOfWildcardOfObject, "other")
      .addStatement("super($N, $N)", "transcodeClass", "other")
      .build();

  ClassName glide = ClassName.get("com.bumptech.glide", "Glide");
  ClassName requestManager = ClassName.get("com.bumptech.glide", "RequestManager");
  MethodSpec secondConstructor =
      MethodSpec.constructorBuilder()
          .addParameter(glide, "glide")
          .addParameter(requestManager, "requestManager")
          .addParameter(classOfTranscodeType, "transcodeClass")
          .addStatement("super($N, $N ,$N)", "glide", "requestManager", "transcodeClass")
          .build();
  return ImmutableList.of(firstConstructor, secondConstructor);
}
项目:GitHub    文件:RequestManagerGenerator.java   
/**
 * Generates overrides of existing RequestManager methods so that they return our generated
 * RequestBuilder subtype.
 */
private MethodSpec generateRequestManagerRequestBuilderMethodOverride(
    ExecutableElement methodToOverride) {
   // We've already verified that this method returns a RequestBuilder and RequestBuilders have
  // exactly one type argument, so this is safe unless those assumptions change.
  TypeMirror typeArgument =
      ((DeclaredType) methodToOverride.getReturnType()).getTypeArguments().get(0);

  ParameterizedTypeName generatedRequestBuilderOfType =
      ParameterizedTypeName.get(generatedRequestBuilderClassName, ClassName.get(typeArgument));

  MethodSpec.Builder builder = ProcessorUtil.overriding(methodToOverride)
      .returns(generatedRequestBuilderOfType)
      .addCode(
          ProcessorUtil.generateCastingSuperCall(
              generatedRequestBuilderOfType, methodToOverride));

  for (AnnotationMirror mirror : methodToOverride.getAnnotationMirrors()) {
    builder.addAnnotation(AnnotationSpec.get(mirror));
  }
  return builder.build();
}
项目:GitHub    文件:RequestManagerGenerator.java   
private MethodSpec generateAdditionalRequestManagerMethodLegacy(
    ExecutableElement extensionMethod) {
   String returnType = processorUtil.findClassValuesFromAnnotationOnClassAsNames(extensionMethod,
      GlideType.class).iterator().next();
  ClassName returnTypeClassName = ClassName.bestGuess(returnType);
  ParameterizedTypeName parameterizedTypeName =
      ParameterizedTypeName.get(generatedRequestBuilderClassName, returnTypeClassName);

  return MethodSpec.methodBuilder(extensionMethod.getSimpleName().toString())
      .addModifiers(Modifier.PUBLIC)
      .returns(parameterizedTypeName)
      .addJavadoc(processorUtil.generateSeeMethodJavadoc(extensionMethod))
      .addStatement(
          "$T requestBuilder = this.as($T.class)", parameterizedTypeName, returnTypeClassName)
      .addStatement("$T.$N(requestBuilder)",
          extensionMethod.getEnclosingElement(), extensionMethod.getSimpleName())
      .addStatement("return requestBuilder")
      .build();
}
项目:arez    文件:ComponentDescriptor.java   
@Nonnull
private MethodSpec buildGetByQueryMethod()
{
  final TypeName entityType = TypeName.get( getElement().asType() );
  final ParameterizedTypeName queryType =
    ParameterizedTypeName.get( ClassName.get( Predicate.class ), entityType );
  return MethodSpec.methodBuilder( "getByQuery" ).
    addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
    addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).
    addParameter( ParameterSpec.builder( queryType, "query", Modifier.FINAL ).
      addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ).
    returns( entityType ).
    addStatement( "final $T entity = findByQuery( query )", entityType ).
    addCode( CodeBlock.builder().
      beginControlFlow( "if ( null == entity )" ).
      addStatement( "throw new $T()", GeneratorUtil.NO_RESULT_EXCEPTION_CLASSNAME ).
      endControlFlow().
      build() ).
    addStatement( "return entity" ).
    build();
}
项目:auto-value-bundle    文件:GsonDeserializer.java   
@Override
public String deserializeUnknownParameterizedObject(
        String readFromBundle,
        ParameterizedTypeName parameterizedTypeName,
        VariableElement deserializerElement) {
    StringBuilder typeToken = new StringBuilder("new ")
            .append(TYPE_TOKEN_FULLY_QUALIFIED)
            .append("<")
            .append(parameterizedTypeName.rawType.simpleName())
            .append("<");
    for (TypeName typeName : parameterizedTypeName.typeArguments) {
        typeToken.append(deserializeParameterizedObject(typeName))
                .append(", ");
    }
    typeToken.deleteCharAt(typeToken.length() - 1);
    typeToken.deleteCharAt(typeToken.length() - 1);

    typeToken.append(">(){}.getType()");

    return CodeBlock.builder()
            .add("$L.$L($L, $L)", deserializerElement.getSimpleName().toString(), "fromJson", readFromBundle,
                    typeToken)
            .build()
            .toString();
}
项目:json-log-domain    文件:LoggerGenerator.java   
public static JavaFile logger(Domain ontology) {
    ClassName name = ClassName.get(ontology.getTargetPackage(), ontology.getName() + LOGGER);

    ClassName statementName = ClassName.get(ontology.getTargetPackage(), ontology.getName() + STATEMENT);

    ParameterSpec loggerParameter = ParameterSpec.builder(org.slf4j.Logger.class, "logger").build();

    return JavaFile.builder(name.packageName(), TypeSpec.classBuilder(name)
        .superclass(ParameterizedTypeName.get(ClassName.get(AbstractDomainLogger.class), statementName))                
        .addJavadoc(composeJavadoc(ontology, name))
        .addModifiers(Modifier.PUBLIC)
        .addMethod(MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addParameter(loggerParameter)
            .addStatement("super($N)", loggerParameter)
            .build())
        .addMethod(getCreateLogStatementMethod(statementName)).build()).build();
}
项目:Witch-Android    文件:OnBindPropertySetter.java   
@Override
public String create() {
    MethodSpec method = MethodSpec.methodBuilder("onBind")
            .addModifiers(Modifier.PUBLIC)
            .addParameter(viewType, "target")
            .addParameter(valueType, "value")
            .returns(void.class)
            .addStatement("$N.$N(value)", "target", getPropertySetter(property))
            .build();

    TypeSpec anonymous = TypeSpec.anonymousClassBuilder("")
            .addSuperinterface(ParameterizedTypeName.get(TypeUtils.SYNC_ON_BIND, viewType, valueType))
            .addMethod(method)
            .build();

    return anonymous.toString();
}
项目:java-code-templates    文件:Validator.java   
@Override
public Void visitVariableAsField(VariableElement element, Trees trees) {

    if (isForEachVariable(element) && Util.hasInitializer(element, trees) && retainTypeFromTemplate(element)) {
        // If we are retaining the type from the template of a static final field,
        // the value has to be initialized with a value passed to a descriptor
        // initialization annotation, which limits the types that can be used.
        TypeName fieldType = TypeName.get(element.asType());
        if (fieldType instanceof ParameterizedTypeName) {
            fieldType = ((ParameterizedTypeName)fieldType).rawType;
        }
        assertThat(fieldType.isPrimitive()
                || STRING_CLASS_NAME.equals(fieldType)
                || CLASS_CLASS_NAME.equals(fieldType), element,
                ValidationMessages.TEMPLATE_INITIALIZED_FOREACH_FIELDS);
    }

    return null;
}
项目:aws-sdk-java-v2    文件:AsyncClientInterface.java   
/**
 * Generates the traditional method for an operation (i.e. one that takes a request and returns a response).
 */
private MethodSpec.Builder traditionalMethod(OperationModel opModel) {
    ClassName responsePojoType = getPojoResponseType(opModel);
    ClassName requestType = ClassName.get(modelPackage, opModel.getInput().getVariableType());

    MethodSpec.Builder builder = methodSignatureWithReturnType(opModel)
            .addParameter(requestType, opModel.getInput().getVariableName())
            .addJavadoc(opModel.getDocs(model, ClientType.ASYNC));

    if (opModel.hasStreamingInput()) {
        builder.addParameter(ClassName.get(AsyncRequestProvider.class), "requestProvider");
    }
    if (opModel.hasStreamingOutput()) {
        builder.addTypeVariable(STREAMING_TYPE_VARIABLE);
        final ParameterizedTypeName asyncResponseHandlerType = ParameterizedTypeName
                .get(ClassName.get(AsyncResponseHandler.class), responsePojoType, STREAMING_TYPE_VARIABLE);
        builder.addParameter(asyncResponseHandlerType, "asyncResponseHandler");
    }

    return operationBody(builder, opModel);
}
项目:dataenum    文件:MapMethods.java   
private MethodSpec.Builder createFoldSignature(Iterable<TypeVariableName> availableTypeVariables)
    throws ParserException {
  MethodSpec.Builder builder =
      MethodSpec.methodBuilder("map")
          .addTypeVariable(FOLD_RETURN_TYPE)
          .addModifiers(Modifier.PUBLIC)
          .returns(FOLD_RETURN_TYPE);

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

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

  return builder;
}
项目:dataenum    文件:MatchMethods.java   
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;
}
项目:aws-sdk-java-v2    文件:AbstractMemberSetters.java   
protected ParameterSpec memberAsBeanStyleParameter() {
    if (memberModel.hasBuilder()) {
        TypeName builderName = poetExtensions.getModelClass(memberModel.getC2jShape()).nestedClass("BuilderImpl");
        return ParameterSpec.builder(builderName, fieldName()).build();
    }
    if (memberModel.isList() && hasBuilder(memberModel.getListModel().getListMemberModel())) {
        TypeName memberName = poetExtensions.getModelClass(memberModel.getListModel().getListMemberModel().getC2jShape())
                                            .nestedClass("BuilderImpl");
        TypeName listType = ParameterizedTypeName.get(ClassName.get(Collection.class), memberName);
        return ParameterSpec.builder(listType, fieldName()).build();
    }
    if (memberModel.isMap() && hasBuilder(memberModel.getMapModel().getValueModel())) {
        TypeName keyType = typeProvider.getTypeNameForSimpleType(memberModel.getMapModel().getKeyModel()
                                                                            .getVariable().getVariableType());
        TypeName valueType = poetExtensions.getModelClass(memberModel.getMapModel().getValueModel().getC2jShape())
                                           .nestedClass("BuilderImpl");
        TypeName mapType = ParameterizedTypeName.get(ClassName.get(Map.class), keyType, valueType);
        return ParameterSpec.builder(mapType, fieldName()).build();
    }

    return memberAsParameter();
}
项目:json2java4idea    文件:JavaConverter.java   
@Nonnull
private TypeName generateListType(@Nonnull String className, @Nonnull JsonValue value, @Nonnull ClassBuilder builder) {
    if (value.isArray()) {
        final JsonValue firstValue = value.asArray()
                .stream()
                .findFirst()
                .orElse(new JsonNull());
        final TypeName type = generateListType(className, firstValue, builder);
        return ParameterizedTypeName.get(ClassName.get(List.class), type);
    }

    if (value.isObject()) {
        final TypeSpec innerClass = fromObject(className, value.asObject(), Modifier.PUBLIC, Modifier.STATIC);
        builder.addInnerType(innerClass);

        final TypeName innerClassType = ClassName.bestGuess(innerClass.name);
        return ParameterizedTypeName.get(ClassName.get(List.class), innerClassType);
    }

    return ParameterizedTypeName.get(ClassName.get(List.class), value.getType().box());
}
项目:domino    文件:EndpointsRegisterMethodWriter.java   
@Override
protected void registerItem(EndpointsEntry entry, MethodSpec.Builder methodBuilder) {
    final FullClassName handlerEndpoint = new FullClassName(entry.element.fullQualifiedNoneGenericName() + "EndpointHandler");
    String path = entry.element.getAnnotation(Handler.class).value();

    ClassName handlerEndpointType = ClassName.get(handlerEndpoint.asPackage(), handlerEndpoint.asSimpleName());
    MethodSpec getMethod = MethodSpec.methodBuilder("get")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(handlerEndpointType)
            .addStatement("return new $T()", handlerEndpointType)
            .build();

    TypeSpec factoryType = TypeSpec.anonymousClassBuilder("")
            .addSuperinterface(ParameterizedTypeName.get(ClassName.get(Supplier.class), handlerEndpointType.box()))
            .addMethod(getMethod)
            .build();
    methodBuilder.addStatement("registry.registerEndpoint(\"" + path + "\", $L)", factoryType);
}
项目:auto-nav    文件:NavProcessor.java   
private void addPreGoListener(TypeSpec.Builder navigatorBuilder){
    MethodSpec onPreGo = MethodSpec.methodBuilder("onPreGo")
            .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
            .returns(boolean.class)
            .addParameter(classContext,"fromContext")
            .addParameter(classIntent, "intent")
            .build();

    TypeSpec preListenerType = TypeSpec.interfaceBuilder(listenerName)
            .addModifiers(Modifier.PUBLIC)
            .addMethod(onPreGo).build();

    TypeName listenerType = ClassName.get(navigatorPackageName, navigatorClassName, listenerName);
    TypeName listenerList = ParameterizedTypeName.get(ClassName.get(ArrayList.class), listenerType);
    navigatorBuilder.addType(preListenerType);
    navigatorBuilder.addField(
            listenerList,
            "preGoListeners",
            Modifier.PRIVATE, Modifier.STATIC);
    navigatorBuilder.addStaticBlock(
            CodeBlock.of(
                    "preGoListeners = new $T();\n" +
                            "$T.setPreGoListeners(preGoListeners);\n", listenerList, ClassName.get("nav.base","BaseIntent")));

    MethodSpec add = MethodSpec.methodBuilder("addPreGoListener").addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .addParameter(listenerType,"listener")
            .addCode("if(listener != null){ preGoListeners.add(listener);}\n")
            .build();

    MethodSpec remove = MethodSpec.methodBuilder("removePreGoListener").addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .addParameter(listenerType,"listener")
            .addCode("if(listener != null){ preGoListeners.remove(listener);}\n")
            .build();

    navigatorBuilder.addMethod(add).addMethod(remove);

}
项目: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();
}
项目:aws-sdk-java-v2    文件:TypeProvider.java   
public TypeName mapEntryType(MapModel mapModel) {
    TypeName keyType;
    if (mapModel.getKeyModel().isSimple()) {
        keyType = getTypeNameForSimpleType(mapModel.getKeyModel().getVariable().getVariableType());
    } else {
        keyType = parameterType(mapModel.getKeyModel());
    }

    TypeName valueType = parameterType(mapModel.getValueModel());
    if (mapModel.getValueModel().isList()) {
        valueType = WildcardTypeName.subtypeOf(valueType);
    }

    return ParameterizedTypeName.get(ClassName.get(Map.Entry.class), keyType, valueType);
}
项目:aws-sdk-java-v2    文件:EnumClass.java   
private MethodSpec knownValuesSpec() {
    return MethodSpec.methodBuilder("knownValues")
                     .returns(ParameterizedTypeName.get(ClassName.get(Set.class), className))
                     .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                     .addJavadoc("Use this in place of {@link #values()} to return a {@link Set} of all values known to the "
                                 + "SDK.\n"
                                 + "This will return all known enum values except {@link #$N}.\n\n"
                                 + "@return a {@link $T} of known {@link $T}s", UNKNOWN_TO_SDK_VERSION, Set.class, className)
                     .addStatement("return $T.of(values()).filter(v -> v != $N).collect(toSet())",
                                   Stream.class,
                                   UNKNOWN_TO_SDK_VERSION)
                     .build();
}
项目:arez    文件:ComponentDescriptor.java   
@Nonnull
private MethodSpec buildFindByQueryMethod()
{
  final ParameterizedTypeName queryType =
    ParameterizedTypeName.get( ClassName.get( Predicate.class ), TypeName.get( getElement().asType() ) );
  return MethodSpec.methodBuilder( "findByQuery" ).
    addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
    addAnnotation( GeneratorUtil.NULLABLE_CLASSNAME ).
    addParameter( ParameterSpec.builder( queryType, "query", Modifier.FINAL ).
      addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ).
    returns( TypeName.get( getElement().asType() ) ).
    addStatement( "return entities().stream().filter( query ).findFirst().orElse( null )", Collectors.class ).
    build();
}
项目:GitHub    文件:RequestManagerGenerator.java   
/**
 * Generates overrides of existing RequestManager methods so that they return our generated
 * RequestBuilder subtype.
 */
private MethodSpec generateRequestManagerMethodOverride(ExecutableElement methodToOverride) {
   // We've already verified that this method returns a RequestBuilder and RequestBuilders have
  // exactly one type argument, so this is safe unless those assumptions change.
  TypeMirror typeArgument =
      ((DeclaredType) methodToOverride.getReturnType()).getTypeArguments().get(0);

  ParameterizedTypeName generatedRequestBuilderOfType =
      ParameterizedTypeName.get(generatedRequestBuilderClassName, ClassName.get(typeArgument));

  return MethodSpec.overriding(methodToOverride)
      .returns(generatedRequestBuilderOfType)
      .addCode(CodeBlock.builder()
          .add("return ($T) super.$N(",
              generatedRequestBuilderOfType, methodToOverride.getSimpleName())
          .add(FluentIterable.from(methodToOverride.getParameters())
              .transform(new Function<VariableElement, String>() {
                @Override
                public String apply(VariableElement input) {
                  return input.getSimpleName().toString();
                }
              })
              .join(Joiner.on(", ")))
          .add(");\n")
          .build())
      .build();
}
项目:arez    文件:ComponentDescriptor.java   
@Nonnull
private MethodSpec buildFindAllByQueryMethod()
{
  final ParameterizedTypeName queryType =
    ParameterizedTypeName.get( ClassName.get( Predicate.class ), TypeName.get( getElement().asType() ) );
  return MethodSpec.methodBuilder( "findAllByQuery" ).
    addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
    addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).
    addParameter( ParameterSpec.builder( queryType, "query", Modifier.FINAL ).
      addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).build() ).
    returns( ParameterizedTypeName.get( ClassName.get( List.class ), TypeName.get( getElement().asType() ) ) ).
    addStatement( "return toList( entities().stream().filter( query ) )", Collectors.class ).
    build();
}
项目:GitHub    文件:RequestBuilderGenerator.java   
/**
 * Overrides the protected downloadOnly method in {@link com.bumptech.glide.RequestBuilder} to
 * return our generated subclass instead.
 */
private MethodSpec generateDownloadOnlyRequestMethod() {
  ParameterizedTypeName generatedRequestBuilderOfFile
      = ParameterizedTypeName.get(generatedRequestBuilderClassName, ClassName.get(File.class));
  return MethodSpec.methodBuilder("getDownloadOnlyRequest")
      .addAnnotation(Override.class)
      .returns(generatedRequestBuilderOfFile)
      .addModifiers(Modifier.PROTECTED)
      .addStatement("return new $T<>($T.class, $N).apply($N)",
          generatedRequestBuilderClassName, File.class, "this",
          "DOWNLOAD_ONLY_OPTIONS")
      .build();
}
项目:MRouter    文件:ProcessorUtils.java   
public static TypeName getTypeName(TypeElement enclosingElement) {
    TypeName targetType = TypeName.get(enclosingElement.asType());
    if (targetType instanceof ParameterizedTypeName) {
        targetType = ((ParameterizedTypeName) targetType).rawType;
    }
    return targetType;
}
项目:GitHub    文件:DelegateClassGenerator.java   
@Override
public JavaFile build() {
    TypeSpec.Builder result =
            TypeSpec.classBuilder(getClassName()).addModifiers(Modifier.PUBLIC)
                    .addSuperinterface(
                            ParameterizedTypeName.get(VIEW_DELEGATE, viewClass,
                                                      getPresenterFactoryTypeName()));
    decorator.build(result);
    return JavaFile.builder(getPackageName(), result.build())
            .addFileComment("Generated class from EasyMVP. Do not modify!").build();
}
项目:GitHub    文件:CustomViewDecorator.java   
@Override
protected MethodSpec.Builder getOnLoaderResetMethod(ParameterizedTypeName loader) {
    return getCallbacksMethod(METHOD_ON_LOADER_RESET)
            .returns(TypeName.VOID)
            .addParameter(loader, "loader")
            .addStatement("delegate.get().detachView()")
            .addStatement("delegate.get().$L = null", FIELD_PRESENTER);
}
项目:GitHub    文件:PresenterLoaderGenerator.java   
@Override
public JavaFile build() {
    TypeSpec.Builder result =
            TypeSpec.classBuilder(getClassName()).addModifiers(Modifier.PUBLIC)
                    .addTypeVariable(TypeVariableName.get("P", Presenter.class))
                    .superclass(ParameterizedTypeName.get(AndroidLoaderUtils.getLoader(supportLibrary),
                                                          TypeVariableName.get("P")));
    addConstructor(result);
    addFields(result);
    addMethods(result);
    return JavaFile.builder(getPackageName(), result.build())
            .addFileComment("Generated class from EasyMVP. Do not modify!").build();
}
项目:android-auto-mapper    文件:TypeUtil.java   
public static Element getGenericElement(Element child, Elements elementUtils) {
    TypeName typeName = (TypeName.get(child.asType()));
    if (typeName instanceof ParameterizedTypeName) {
        List<TypeName> typeNames = ((ParameterizedTypeName) typeName).typeArguments;
        if (typeNames != null && typeNames.size() > 0) {
            child = elementUtils.getTypeElement(typeNames.get(0).toString());
        }
    }
    return child;
}
项目:arez    文件:ComponentDescriptor.java   
@Nonnull
private MethodSpec buildEntitiesMethod()
{
  return MethodSpec.methodBuilder( "entities" ).
    addModifiers( Modifier.PROTECTED ).
    addAnnotation( AnnotationSpec.builder( ClassName.bestGuess( Constants.OBSERVABLE_ANNOTATION_CLASSNAME ) ).
      addMember( "expectSetter", "false" ).build() ).
    addJavadoc( "Return the raw collection of entities in the repository.\n" +
                "This collection should not be exposed to the user but may be used be repository extensions when\n" +
                "they define custom queries. NOTE: use of this method marks the list as observed.\n" ).
    addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ).
    returns( ParameterizedTypeName.get( ClassName.get( Collection.class ), TypeName.get( getElement().asType() ) ) ).
    addStatement( "return $N", ENTITYLIST_FIELD_NAME ).
    build();
}
项目:GitHub    文件:AppModuleGenerator.java   
private MethodSpec generateGetExcludedModuleClasses(Set<String> excludedClassNames) {
  TypeName wildCardOfObject = WildcardTypeName.subtypeOf(Object.class);
  ParameterizedTypeName classOfWildcardOfObjet =
      ParameterizedTypeName.get(ClassName.get(Class.class), wildCardOfObject);
  ParameterizedTypeName setOfClassOfWildcardOfObject =
      ParameterizedTypeName.get(ClassName.get(Set.class), classOfWildcardOfObjet);
  ParameterizedTypeName hashSetOfClassOfWildcardOfObject =
      ParameterizedTypeName.get(ClassName.get(HashSet.class), classOfWildcardOfObjet);
  MethodSpec.Builder builder = MethodSpec.methodBuilder("getExcludedModuleClasses")
      .addModifiers(Modifier.PUBLIC)
      .addAnnotation(Override.class)
      .returns(setOfClassOfWildcardOfObject);

  if (excludedClassNames.isEmpty()) {
    builder.addStatement("return $T.emptySet()", Collections.class);
  } else {
    builder.addStatement(
        "$T excludedClasses = new $T()", setOfClassOfWildcardOfObject,
        hashSetOfClassOfWildcardOfObject);
    for (String excludedClassName : excludedClassNames) {
      // TODO: Remove this when we no longer support manifest parsing.
      // Using a Literal ($L) instead of a type ($T) to get a fully qualified import that allows
      // us to suppress deprecation warnings. Aimed at deprecated GlideModules.
      builder.addStatement("excludedClasses.add($L.class)", excludedClassName);
    }
    builder.addStatement("return excludedClasses");
  }

  return builder.build();
}
项目:aws-sdk-java-v2    文件:PaginatorResponseClassSpec.java   
/**
 * A {@link MethodSpec} for the overridden iterator() method which is inherited
 * from the interface.
 */
private MethodSpec iteratorMethod() {
    return MethodSpec.methodBuilder("iterator")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(ParameterizedTypeName.get(ClassName.get(Iterator.class), responseType()))
            .addStatement("return new $T($L)", PaginatedResponsesIterator.class, NEXT_PAGE_FETCHER_MEMBER)
            .build();
}
项目:GitHub    文件:JsonObjectHolder.java   
public TypeName getParameterizedParentTypeName() {
    if (parentUsedTypeParameters.size() > 0) {
        List<TypeName> usedParameters = new ArrayList<>();
        for (String parameter : parentUsedTypeParameters) {
            if (parameter.indexOf(".") > 0) {
                usedParameters.add(ClassName.bestGuess(parameter));
            } else {
                usedParameters.add(TypeVariableName.get(parameter));
            }
        }
        return ParameterizedTypeName.get((ClassName)parentTypeName, usedParameters.toArray(new TypeName[usedParameters.size()]));
    } else {
        return parentTypeName;
    }
}
项目:aws-sdk-java-v2    文件:JsonProtocolSpec.java   
@Override
public Optional<MethodSpec> createErrorResponseHandler() {
    ClassName httpResponseHandler = ClassName.get(HttpResponseHandler.class);
    ClassName sdkBaseException = ClassName.get(SdkServiceException.class);
    TypeName responseHandlerOfException = ParameterizedTypeName.get(httpResponseHandler, sdkBaseException);

    return Optional.of(MethodSpec.methodBuilder("createErrorResponseHandler")
                                 .returns(responseHandlerOfException)
                                 .addModifiers(Modifier.PRIVATE)
                                 .addStatement("return protocolFactory.createErrorResponseHandler(new $T())",
                                               JsonErrorResponseMetadata.class)
                                 .build());
}
项目:json-log-domain    文件:MdcGenerator.java   
public static JavaFile statement(Domain ontology) {

    ClassName name = ClassName.get(ontology.getTargetPackage(), ontology.getName() + MARKER_MDC);

    ClassName markerName = MarkerGenerator.getName(ontology);

    TypeName wildcard = WildcardTypeName.subtypeOf(DomainMarker.class);
    TypeName classOfAny = ParameterizedTypeName.get(ClassName.get(Class.class), wildcard);

    ParameterSpec type = ParameterSpec.builder(classOfAny, "type").build();

    return JavaFile.builder(name.packageName(), TypeSpec.classBuilder(name)
                .superclass(ParameterizedTypeName.get( ClassName.get(DomainMdc.class), markerName))
                .addModifiers(Modifier.PUBLIC)
                .addMethod(MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PUBLIC)
                    .addStatement("super($T.QUALIFIER)", markerName)
                    .build()
                )
                .addMethod(MethodSpec.methodBuilder("createMarker")
                        .addModifiers(Modifier.PUBLIC)
                        .addStatement("return new $T()", markerName)
                        .returns(markerName)
                        .build()
                    )
                .addMethod(MethodSpec.methodBuilder("supports")
                        .addModifiers(Modifier.PUBLIC)
                        .addParameter(type)
                        .addStatement("return $T.class == $N", markerName, type)
                        .returns(boolean.class)
                        .build()
                    )
                .build())

            .build();
}
项目:react4j    文件:Generator.java   
private static FieldSpec.Builder buildProviderField( final @Nonnull ComponentDescriptor descriptor )
{
  return FieldSpec.builder( ParameterizedTypeName.get( PROVIDER_CLASSNAME,
                                                       TypeName.get( descriptor.getDeclaredType() ) ),
                            "c_provider",
                            Modifier.STATIC,
                            Modifier.PRIVATE );
}
项目:aws-sdk-java-v2    文件:BeanGetterHelper.java   
private MethodSpec mapOfBuildersGetter(MemberModel memberModel) {
    TypeName keyType = typeProvider.getTypeNameForSimpleType(memberModel.getMapModel().getKeyModel()
                                                                        .getVariable().getVariableType());
    ClassName valueType = poetExtensions.getModelClass(memberModel.getMapModel().getValueModel().getC2jShape());
    TypeName returnType = ParameterizedTypeName.get(ClassName.get(Map.class), keyType, valueType.nestedClass("Builder"));

    return basicGetter(memberModel,
                       returnType,
                       "return $1N != null ? $2T.mapValues($1N, $3T::toBuilder) : null",
                       memberModel.getVariable().getVariableName(),
                       CollectionUtils.class,
                       valueType);
}
项目:react4j    文件:Generator.java   
@Nonnull
private static MethodSpec.Builder buildSetProviderMethod( @Nonnull final ComponentDescriptor descriptor )
{
  return MethodSpec.methodBuilder( "setProvider" ).
    addModifiers( Modifier.STATIC ).
    addParameter( ParameterizedTypeName.get( PROVIDER_CLASSNAME,
                                             TypeName.get( descriptor.getDeclaredType() ) ),
                  "provider",
                  Modifier.FINAL ).
    addStatement( "c_provider = provider" );
}
项目:react4j    文件:Generator.java   
@Nonnull
private static MethodSpec.Builder buildGetProviderMethod( @Nonnull final ComponentDescriptor descriptor )
{
  return MethodSpec.methodBuilder( "getProvider" ).
    addModifiers( Modifier.PRIVATE, Modifier.STATIC ).
    returns( ParameterizedTypeName.get( PROVIDER_CLASSNAME, TypeName.get( descriptor.getDeclaredType() ) ) ).
    addStatement( "$T.invariant( () -> null != c_provider, () -> \"Attempted to create an instance of the React4j " +
                  "component named '$N' before the dependency injection provider has been initialized. Please see " +
                  "the documentation at https://react4j.github.io/dependency_injection for directions how to " +
                  "configure dependency injection.\" )",
                  GUARDS_CLASSNAME,
                  descriptor.getName() ).
    addStatement( "return c_provider" );
}
项目:Witch-Android    文件:NewViewBinderInstance.java   
@Override
public TypeSpec.Builder builder() {
    return TypeSpec.anonymousClassBuilder("$L", viewId)
            .addSuperinterface(ParameterizedTypeName.get(VIEW_BINDER, targetTypeName, viewTypeName, valueTypeName, viewHolderTypeName))
            .addField(TypeUtils.BINDER, "binder", Modifier.PROTECTED);

}
项目:auto-adapter    文件:ViewBinderGenerator.java   
private TypeSpec.Builder createClassBuilder(final TypeElement model, final ClassName viewBinderClassName) {
    TypeName modelType = ParameterizedTypeName.get(model.asType());
    ParameterizedTypeName viewHolderBinderTypeName = ParameterizedTypeName.get(VIEW_BINDER_NAME, modelType);

    return TypeSpec.classBuilder(viewBinderClassName).addModifiers(Modifier.FINAL).addSuperinterface(
            viewHolderBinderTypeName);
}