コード例 #1
0
  @Override
  public void generateContentValuesBuilderMethod(
      TypeSpec.Builder builder, TypeName type, String contentValuesVarName) {

    builder.addMethod(
        MethodSpec.methodBuilder(field.getFieldName())
            .addJavadoc("Adds the given value to this ContentValues\n")
            .addJavadoc("@param value The value\n")
            .addJavadoc("@return $T\n", type)
            .addModifiers(Modifier.PUBLIC)
            .addParameter(TypeName.get(field.getField().asType()), "value", Modifier.FINAL)
            .returns(type)
            .addStatement("$L.put($S, value)", contentValuesVarName, field.getColumnName())
            .addStatement("return this")
            .build());

    builder.addMethod(
        MethodSpec.methodBuilder(field.getFieldName() + "AsNull")
            .addJavadoc("Adds a null value to this ContentValues\n")
            .addJavadoc("@return $T\n", type)
            .addModifiers(Modifier.PUBLIC)
            .returns(type)
            .addStatement("$L.putNull( $S )", contentValuesVarName, field.getColumnName())
            .addStatement("return this")
            .build());
  }
コード例 #2
0
ファイル: MapKeyGenerator.java プロジェクト: llp/dagger
  @Override
  Optional<TypeSpec.Builder> write(
      ClassName generatedTypeName, MapKeyCreatorSpecification mapKeyCreatorType) {
    TypeSpec.Builder mapKeyCreatorBuilder =
        classBuilder(generatedTypeName.simpleName()).addModifiers(PUBLIC, FINAL);

    for (TypeElement annotationElement :
        nestedAnnotationElements(mapKeyCreatorType.annotationElement())) {
      mapKeyCreatorBuilder.addMethod(buildCreateMethod(generatedTypeName, annotationElement));
    }

    return Optional.of(mapKeyCreatorBuilder);
  }
コード例 #3
0
  private void generate(RestActionClass actionClass) {
    TypeSpec.Builder classBuilder =
        TypeSpec.classBuilder(actionClass.getHelperName())
            .addModifiers(Modifier.PUBLIC)
            .addJavadoc("SantaRest compile time, autogenerated class, which fills actions")
            .addSuperinterface(
                ParameterizedTypeName.get(
                    ClassName.get(SantaRest.ActionHelper.class), actionClass.getTypeName()));

    classBuilder.addMethod(createRequestMethod(actionClass));
    classBuilder.addMethod(createFillResponseMethod(actionClass));
    classBuilder.addMethod(createFillErrorMethod(actionClass));
    saveClass(actionClass.getPackageName(), classBuilder.build());
  }
コード例 #4
0
ファイル: CodeGenerator.java プロジェクト: mkodekar/Java-NoOp
  TypeSpec brewJava() {
    String className = CLASS_PREFIX + noOpAnnotatedInterface.simpleName();
    TypeSpec.Builder builder = classBuilder(className);

    Modifier visibilityModifier = noOpAnnotatedInterface.visibility();
    if (visibilityModifier != null) {
      builder.addModifiers(visibilityModifier);
    }

    builder.addSuperinterface(noOpAnnotatedInterface.interfaceType());
    for (ExecutableElement method : noOpAnnotatedInterface.methods()) {
      builder.addMethod(generateMethod(method));
    }

    return builder.build();
  }
コード例 #5
0
ファイル: FactoryGenerator.java プロジェクト: llp/dagger
 private void addConstructorParameterAndTypeField(
     TypeName typeName,
     String variableName,
     TypeSpec.Builder factoryBuilder,
     MethodSpec.Builder constructorBuilder) {
   FieldSpec field = FieldSpec.builder(typeName, variableName, PRIVATE, FINAL).build();
   factoryBuilder.addField(field);
   ParameterSpec parameter = ParameterSpec.builder(typeName, variableName).build();
   constructorBuilder.addParameter(parameter);
   constructorBuilder.addCode("assert $1N != null; this.$2N = $1N;", parameter, field);
 }
コード例 #6
0
  @Override
  public TypeSpec buildTypeSpec() {
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(schema.getSchemaClassName().simpleName());
    classBuilder.addModifiers(Modifier.PUBLIC);
    classBuilder.addSuperinterface(Types.getSchema(schema.getModelClassName()));

    classBuilder.addFields(buildFieldSpecs());
    classBuilder.addMethods(buildMethodSpecs());

    return classBuilder.build();
  }
コード例 #7
0
ファイル: NoopClass.java プロジェクト: pijpijpij/Noopetal
  /** The access modifier is that of the sourceType. */
  @NonNull
  @Override
  public TypeSpec getTypeSpec() {
    TypeSpec.Builder result = TypeSpec.classBuilder(getTypeName());
    sourceType.applyAccessModifier(result);
    sourceType.applyTypeVariables(result);
    result.addJavadoc(createGeneratedAnnotation(processorClass).toString());
    result.addJavadoc("\n");
    result.addSuperinterface(getDecoratedTypeName());

    for (Element element : sourceType.getAllEnclosedElements()) {
      if (element.getKind() == ElementKind.METHOD) {
        MethodSpec method = createOverridingMethod((ExecutableElement) element).build();
        result.addMethod(method);
      }
    }

    return result.build();
  }
コード例 #8
0
  @Override
  public void onWriteDefinition(TypeSpec.Builder typeBuilder) {

    typeBuilder.addField(
        FieldSpec.builder(
                ClassName.get(String.class),
                AUTHORITY,
                Modifier.PRIVATE,
                Modifier.STATIC,
                Modifier.FINAL)
            .initializer("$S", authority)
            .build());

    int code = 0;
    for (TableEndpointDefinition endpointDefinition : endpointDefinitions) {
      for (ContentUriDefinition contentUriDefinition : endpointDefinition.contentUriDefinitions) {
        typeBuilder.addField(
            FieldSpec.builder(
                    TypeName.INT,
                    contentUriDefinition.name,
                    Modifier.PRIVATE,
                    Modifier.STATIC,
                    Modifier.FINAL)
                .initializer(String.valueOf(code))
                .build());
        code++;
      }
    }

    FieldSpec.Builder uriField =
        FieldSpec.builder(
            ClassNames.URI_MATCHER, URI_MATCHER, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL);

    CodeBlock.Builder initializer =
        CodeBlock.builder()
            .addStatement("new $T($T.NO_MATCH)", ClassNames.URI_MATCHER, ClassNames.URI_MATCHER)
            .add("static {\n");

    for (TableEndpointDefinition endpointDefinition : endpointDefinitions) {
      for (ContentUriDefinition contentUriDefinition : endpointDefinition.contentUriDefinitions) {
        String path;
        if (contentUriDefinition.path != null) {
          path = "\"" + contentUriDefinition.path + "\"";
        } else {
          path =
              CodeBlock.builder()
                  .add(
                      "$L.$L.getPath()",
                      contentUriDefinition.elementClassName,
                      contentUriDefinition.name)
                  .build()
                  .toString();
        }
        initializer.addStatement(
            "$L.addURI($L, $L, $L)", URI_MATCHER, AUTHORITY, path, contentUriDefinition.name);
      }
    }
    initializer.add("}\n");
    typeBuilder.addField(uriField.initializer(initializer.build()).build());

    typeBuilder.addMethod(
        MethodSpec.methodBuilder("getDatabaseName")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addStatement("return $S", databaseNameString)
            .returns(ClassName.get(String.class))
            .build());

    MethodSpec.Builder getTypeBuilder =
        MethodSpec.methodBuilder("getType")
            .addAnnotation(Override.class)
            .addParameter(ClassNames.URI, "uri")
            .returns(ClassName.get(String.class))
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL);

    CodeBlock.Builder getTypeCode =
        CodeBlock.builder()
            .addStatement("$T type = null", ClassName.get(String.class))
            .beginControlFlow("switch($L.match(uri))", URI_MATCHER);

    for (TableEndpointDefinition tableEndpointDefinition : endpointDefinitions) {
      for (ContentUriDefinition uriDefinition : tableEndpointDefinition.contentUriDefinitions) {
        getTypeCode
            .beginControlFlow("case $L:", uriDefinition.name)
            .addStatement("type = $S", uriDefinition.type)
            .addStatement("break")
            .endControlFlow();
      }
    }
    getTypeCode
        .beginControlFlow("default:")
        .addStatement(
            "throw new $T($S + $L)",
            ClassName.get(IllegalArgumentException.class),
            "Unknown URI",
            "uri")
        .endControlFlow();
    getTypeCode.endControlFlow();
    getTypeCode.addStatement("return type");

    getTypeBuilder.addCode(getTypeCode.build());
    typeBuilder.addMethod(getTypeBuilder.build());

    for (MethodDefinition method : methods) {
      MethodSpec methodSpec = method.getMethodSpec();
      if (methodSpec != null) {
        typeBuilder.addMethod(methodSpec);
      }
    }
  }
コード例 #9
0
  public static DeriveResult<DerivedCodeSpec> derive(
      AlgebraicDataType adt, DeriveContext deriveContext, DeriveUtils deriveUtils) {

    // skip constructors for enums
    if (adt.typeConstructor().declaredType().asElement().getKind() == ElementKind.ENUM) {
      return result(none());
    }

    TypeConstructor typeConstructor = adt.typeConstructor();
    TypeElement lazyTypeElement =
        FlavourImpl.findF0(deriveContext.flavour(), deriveUtils.elements());
    TypeName lazyArgTypeName =
        TypeName.get(
            deriveUtils.types().getDeclaredType(lazyTypeElement, typeConstructor.declaredType()));
    String lazyArgName = Utils.uncapitalize(typeConstructor.typeElement().getSimpleName());
    TypeName typeName = TypeName.get(typeConstructor.declaredType());

    List<TypeVariableName> typeVariableNames =
        adt.typeConstructor()
            .typeVariables()
            .stream()
            .map(TypeVariableName::get)
            .collect(Collectors.toList());

    String className = "Lazy";
    TypeSpec.Builder typeSpecBuilder =
        TypeSpec.classBuilder(className)
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .addTypeVariables(typeVariableNames)
            .addField(
                FieldSpec.builder(
                        TypeName.get(Object.class), "lock", Modifier.PRIVATE, Modifier.FINAL)
                    .initializer("new Object()")
                    .build())
            .addField(FieldSpec.builder(lazyArgTypeName, "expression", Modifier.PRIVATE).build())
            .addField(
                FieldSpec.builder(typeName, "evaluation", Modifier.PRIVATE, Modifier.VOLATILE)
                    .build())
            .addMethod(
                MethodSpec.constructorBuilder()
                    .addParameter(ParameterSpec.builder(lazyArgTypeName, lazyArgName).build())
                    .addStatement("this.expression = $N", lazyArgName)
                    .build())
            .addMethod(
                MethodSpec.methodBuilder("eval")
                    .addModifiers(Modifier.PRIVATE)
                    .returns(typeName)
                    .addCode(
                        CodeBlock.builder()
                            .addStatement("$T _evaluation = this.evaluation", typeName)
                            .beginControlFlow("if (_evaluation == null)")
                            .beginControlFlow("synchronized (this.lock)")
                            .addStatement("_evaluation = this.evaluation")
                            .beginControlFlow("if (_evaluation == null)")
                            .addStatement(
                                "this.evaluation = _evaluation = expression.$L()",
                                Utils.getAbstractMethods(lazyTypeElement.getEnclosedElements())
                                    .get(0)
                                    .getSimpleName())
                            .addStatement("this.expression = null")
                            .endControlFlow()
                            .endControlFlow()
                            .endControlFlow()
                            .addStatement("return _evaluation")
                            .build())
                    .build())
            .addMethod(
                Utils.overrideMethodBuilder(adt.matchMethod().element())
                    .addStatement(
                        "return this.eval().$L($L)",
                        adt.matchMethod().element().getSimpleName(),
                        Utils.asArgumentsStringOld(adt.matchMethod().element().getParameters()))
                    .build());

    if (adt.typeConstructor().declaredType().asElement().getKind() == ElementKind.INTERFACE) {
      typeSpecBuilder.addSuperinterface(typeName);
    } else {
      typeSpecBuilder.superclass(typeName);
    }

    typeSpecBuilder.addMethods(
        optionalAsStream(
                findAbstractEquals(typeConstructor.typeElement(), deriveUtils.elements())
                    .map(
                        equals ->
                            deriveUtils
                                .overrideMethodBuilder(equals)
                                .addStatement(
                                    "return this.eval().equals($L)",
                                    equals.getParameters().get(0).getSimpleName())
                                .build()))
            .collect(Collectors.toList()));

    typeSpecBuilder.addMethods(
        optionalAsStream(
                findAbstractHashCode(typeConstructor.typeElement(), deriveUtils.elements())
                    .map(
                        hashCode ->
                            deriveUtils
                                .overrideMethodBuilder(hashCode)
                                .addStatement("return this.eval().hashCode()")
                                .build()))
            .collect(Collectors.toList()));

    typeSpecBuilder.addMethods(
        optionalAsStream(
                findAbstractToString(typeConstructor.typeElement(), deriveUtils.elements())
                    .map(
                        toString ->
                            deriveUtils
                                .overrideMethodBuilder(toString)
                                .addStatement("return this.eval().toString()")
                                .build()))
            .collect(Collectors.toList()));

    return result(
        codeSpec(
            typeSpecBuilder.build(),
            MethodSpec.methodBuilder("lazy")
                .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                .addTypeVariables(
                    typeConstructor
                        .typeVariables()
                        .stream()
                        .map(TypeVariableName::get)
                        .collect(Collectors.toList()))
                .addParameter(lazyArgTypeName, lazyArgName)
                .returns(typeName)
                .addStatement(
                    "return new $L$L($L)",
                    className,
                    typeVariableNames.isEmpty() ? "" : "<>",
                    lazyArgName)
                .build()));
  }
コード例 #10
0
ファイル: FactoryGenerator.java プロジェクト: llp/dagger
  @Override
  Optional<TypeSpec.Builder> write(ClassName generatedTypeName, ProvisionBinding binding) {
    // We don't want to write out resolved bindings -- we want to write out the generic version.
    checkState(!binding.unresolved().isPresent());

    TypeMirror keyType =
        binding.contributionType().equals(ContributionType.MAP)
            ? MapType.from(binding.key().type()).unwrappedValueType(Provider.class)
            : binding.key().type();
    TypeName providedTypeName = TypeName.get(keyType);
    ParameterizedTypeName parameterizedFactoryName = factoryOf(providedTypeName);
    Optional<ParameterizedTypeName> factoryOfRawTypeName = Optional.absent();
    TypeSpec.Builder factoryBuilder;
    Optional<MethodSpec.Builder> constructorBuilder = Optional.absent();
    ImmutableList<TypeVariableName> typeParameters = bindingTypeElementTypeVariableNames(binding);
    ImmutableMap<BindingKey, FrameworkField> fields =
        generateBindingFieldsForDependencies(dependencyRequestMapper, binding);
    switch (binding.factoryCreationStrategy()) {
      case ENUM_INSTANCE:
        factoryBuilder = enumBuilder(generatedTypeName.simpleName()).addEnumConstant("INSTANCE");
        // If we have type parameters, then remove the parameters from our providedTypeName,
        // since we'll be implementing an erased version of it.
        if (!typeParameters.isEmpty()) {
          factoryBuilder.addAnnotation(SUPPRESS_WARNINGS_RAWTYPES);
          // TODO(ronshapiro): instead of reassigning, introduce an optional/second parameter
          providedTypeName = ((ParameterizedTypeName) providedTypeName).rawType;
          factoryOfRawTypeName = Optional.of(factoryOf(providedTypeName));
        }
        break;
      case CLASS_CONSTRUCTOR:
        factoryBuilder =
            classBuilder(generatedTypeName.simpleName())
                .addTypeVariables(typeParameters)
                .addModifiers(FINAL);
        constructorBuilder = Optional.of(constructorBuilder().addModifiers(PUBLIC));
        if (binding.bindingKind().equals(PROVISION)
            && !binding.bindingElement().getModifiers().contains(STATIC)) {
          addConstructorParameterAndTypeField(
              TypeName.get(binding.bindingTypeElement().asType()),
              "module",
              factoryBuilder,
              constructorBuilder.get());
        }
        for (FrameworkField bindingField : fields.values()) {
          addConstructorParameterAndTypeField(
              bindingField.javapoetFrameworkType(),
              bindingField.name(),
              factoryBuilder,
              constructorBuilder.get());
        }
        break;
      default:
        throw new AssertionError();
    }

    factoryBuilder
        .addModifiers(PUBLIC)
        .addSuperinterface(factoryOfRawTypeName.or(parameterizedFactoryName));

    // If constructing a factory for @Inject or @Provides bindings, we use a static create method
    // so that generated components can avoid having to refer to the generic types
    // of the factory.  (Otherwise they may have visibility problems referring to the types.)
    Optional<MethodSpec> createMethod;
    switch (binding.bindingKind()) {
      case INJECTION:
      case PROVISION:
        // The return type is usually the same as the implementing type, except in the case
        // of enums with type variables (where we cast).
        MethodSpec.Builder createMethodBuilder =
            methodBuilder("create")
                .addModifiers(PUBLIC, STATIC)
                .addTypeVariables(typeParameters)
                .returns(parameterizedFactoryName);
        List<ParameterSpec> params =
            constructorBuilder.isPresent()
                ? constructorBuilder.get().build().parameters
                : ImmutableList.<ParameterSpec>of();
        createMethodBuilder.addParameters(params);
        switch (binding.factoryCreationStrategy()) {
          case ENUM_INSTANCE:
            if (typeParameters.isEmpty()) {
              createMethodBuilder.addStatement("return INSTANCE");
            } else {
              // We use an unsafe cast here because the types are different.
              // It's safe because the type is never referenced anywhere.
              createMethodBuilder.addStatement("return ($T) INSTANCE", TypeNames.FACTORY);
              createMethodBuilder.addAnnotation(SUPPRESS_WARNINGS_UNCHECKED);
            }
            break;

          case CLASS_CONSTRUCTOR:
            createMethodBuilder.addStatement(
                "return new $T($L)",
                javapoetParameterizedGeneratedTypeNameForBinding(binding),
                makeParametersCodeBlock(Lists.transform(params, CodeBlocks.PARAMETER_NAME)));
            break;
          default:
            throw new AssertionError();
        }
        createMethod = Optional.of(createMethodBuilder.build());
        break;
      default:
        createMethod = Optional.absent();
    }

    if (constructorBuilder.isPresent()) {
      factoryBuilder.addMethod(constructorBuilder.get().build());
    }

    List<CodeBlock> parameters = Lists.newArrayList();
    for (DependencyRequest dependency : binding.dependencies()) {
      parameters.add(
          frameworkTypeUsageStatement(
              CodeBlocks.format("$L", fields.get(dependency.bindingKey()).name()),
              dependency.kind()));
    }
    CodeBlock parametersCodeBlock = makeParametersCodeBlock(parameters);

    MethodSpec.Builder getMethodBuilder =
        methodBuilder("get")
            .returns(providedTypeName)
            .addAnnotation(Override.class)
            .addModifiers(PUBLIC);

    if (binding.bindingKind().equals(PROVISION)) {
      CodeBlock.Builder providesMethodInvocationBuilder = CodeBlock.builder();
      if (binding.bindingElement().getModifiers().contains(STATIC)) {
        providesMethodInvocationBuilder.add("$T", ClassName.get(binding.bindingTypeElement()));
      } else {
        providesMethodInvocationBuilder.add("module");
      }
      providesMethodInvocationBuilder.add(
          ".$L($L)", binding.bindingElement().getSimpleName(), parametersCodeBlock);
      CodeBlock providesMethodInvocation = providesMethodInvocationBuilder.build();

      if (binding.provisionType().equals(SET)) {
        TypeName paramTypeName =
            TypeName.get(MoreTypes.asDeclared(keyType).getTypeArguments().get(0));
        // TODO(cgruber): only be explicit with the parameter if paramType contains wildcards.
        getMethodBuilder.addStatement(
            "return $T.<$T>singleton($L)",
            Collections.class,
            paramTypeName,
            providesMethodInvocation);
      } else if (binding.nullableType().isPresent()
          || nullableValidationType.equals(Diagnostic.Kind.WARNING)) {
        if (binding.nullableType().isPresent()) {
          getMethodBuilder.addAnnotation((ClassName) TypeName.get(binding.nullableType().get()));
        }
        getMethodBuilder.addStatement("return $L", providesMethodInvocation);
      } else {
        String failMsg = CANNOT_RETURN_NULL_FROM_NON_NULLABLE_PROVIDES_METHOD;
        getMethodBuilder
            .addStatement(
                "$T provided = $L", getMethodBuilder.build().returnType, providesMethodInvocation)
            .addCode("if (provided == null) { ")
            .addStatement("throw new $T($S)", NullPointerException.class, failMsg)
            .addCode("}")
            .addStatement("return provided");
      }
    } else if (binding.membersInjectionRequest().isPresent()) {
      getMethodBuilder.addStatement(
          "$1T instance = new $1T($2L)", providedTypeName, parametersCodeBlock);
      getMethodBuilder.addStatement(
          "$L.injectMembers(instance)",
          fields.get(binding.membersInjectionRequest().get().bindingKey()).name());
      getMethodBuilder.addStatement("return instance");
    } else {
      getMethodBuilder.addStatement("return new $T($L)", providedTypeName, parametersCodeBlock);
    }

    factoryBuilder.addMethod(getMethodBuilder.build());
    if (createMethod.isPresent()) {
      factoryBuilder.addMethod(createMethod.get());
    }

    // TODO(gak): write a sensible toString
    return Optional.of(factoryBuilder);
  }
コード例 #11
0
  private TypeSpec build(ScopeSpec spec) {
    MethodSpec configureScopeSpec =
        MethodSpec.methodBuilder("configureScope")
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(Override.class)
            .addParameter(ClassName.get(MortarScope.Builder.class), "builder")
            .addParameter(ClassName.get(MortarScope.class), "parentScope")
            .addCode(
                CodeBlock.builder()
                    .add(
                        "builder.withService($T.SERVICE_NAME, $T.builder()\n",
                        DAGGERSERVICE_CLS,
                        spec.getDaggerComponentTypeName())
                    .indent()
                    .add(
                        ".$L(parentScope.<$T>getService($T.SERVICE_NAME))\n",
                        spec.getDaggerComponentBuilderDependencyMethodName(),
                        spec.getDaggerComponentBuilderDependencyTypeName(),
                        DAGGERSERVICE_CLS)
                    .add(".module(new Module())\n")
                    .add(".build());\n")
                    .unindent()
                    .build())
            .build();

    List<FieldSpec> fieldSpecs = new ArrayList<>();
    for (ParameterSpec parameterSpec : spec.getModuleSpec().getInternalParameters()) {
      fieldSpecs.add(FieldSpec.builder(parameterSpec.type, parameterSpec.name).build());
    }

    MethodSpec.Builder constructorBuilder =
        MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(AnnotationSpec.builder(ParcelConstructor.class).build())
            .addParameters(spec.getModuleSpec().getInternalParameters());
    for (ParameterSpec parameterSpec : spec.getModuleSpec().getInternalParameters()) {
      constructorBuilder.addStatement("this.$L = $L", parameterSpec.name, parameterSpec.name);
    }

    TypeSpec.Builder builder =
        TypeSpec.classBuilder(spec.getClassName().simpleName())
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(
                AnnotationSpec.builder(Generated.class)
                    .addMember(
                        "value",
                        "$S",
                        architect.autostack.compiler.AnnotationProcessor.class.getName())
                    .build())
            .addAnnotation(spec.getComponentAnnotationSpec())
            .addAnnotation(
                AnnotationSpec.builder(Parcel.class).addMember("parcelsIndex", "false").build())
            .addType(buildModule(spec.getModuleSpec()))
            .addMethod(constructorBuilder.build())
            .addMethod(configureScopeSpec)
            .addFields(fieldSpecs);

    if (spec.getScopeAnnotationSpec() != null) {
      builder.addAnnotation(spec.getScopeAnnotationSpec());
    }

    if (spec.getPathViewTypeName() != null) {
      builder.addSuperinterface(PATH_CLS);
      MethodSpec createViewSpec =
          MethodSpec.methodBuilder("createView")
              .addModifiers(Modifier.PUBLIC)
              .returns(spec.getPathViewTypeName())
              .addAnnotation(Override.class)
              .addParameter(CONTEXT_CLS, "context")
              .addStatement("return new $T(context)", spec.getPathViewTypeName())
              .build();

      builder.addMethod(createViewSpec);
    } else {
      builder.addSuperinterface(STACKABLE_CLS);
    }

    return builder.build();
  }
コード例 #12
0
  @Override
  Optional<TypeSpec.Builder> write(ClassName generatedTypeName, MembersInjectionBinding binding) {
    // Empty members injection bindings are special and don't need source files.
    if (binding.injectionSites().isEmpty()) {
      return Optional.absent();
    }
    // We don't want to write out resolved bindings -- we want to write out the generic version.
    checkState(!binding.unresolved().isPresent());

    ImmutableList<TypeVariableName> typeParameters = bindingTypeElementTypeVariableNames(binding);
    TypeSpec.Builder injectorTypeBuilder =
        TypeSpec.classBuilder(generatedTypeName.simpleName())
            .addModifiers(PUBLIC, FINAL)
            .addTypeVariables(typeParameters);

    TypeName injectedTypeName = TypeName.get(binding.key().type());
    TypeName implementedType = membersInjectorOf(injectedTypeName);
    injectorTypeBuilder.addSuperinterface(implementedType);

    MethodSpec.Builder injectMembersBuilder =
        MethodSpec.methodBuilder("injectMembers")
            .returns(TypeName.VOID)
            .addModifiers(PUBLIC)
            .addAnnotation(Override.class)
            .addParameter(injectedTypeName, "instance")
            .addCode("if (instance == null) {")
            .addStatement(
                "throw new $T($S)",
                NullPointerException.class,
                "Cannot inject members into a null reference")
            .addCode("}");

    ImmutableMap<BindingKey, FrameworkField> fields =
        SourceFiles.generateBindingFieldsForDependencies(dependencyRequestMapper, binding);

    ImmutableMap.Builder<BindingKey, FieldSpec> dependencyFieldsBuilder = ImmutableMap.builder();

    MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder().addModifiers(PUBLIC);

    // We use a static create method so that generated components can avoid having
    // to refer to the generic types of the factory.
    // (Otherwise they may have visibility problems referring to the types.)
    MethodSpec.Builder createMethodBuilder =
        MethodSpec.methodBuilder("create")
            .returns(implementedType)
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .addTypeVariables(typeParameters);

    createMethodBuilder.addCode(
        "return new $T(", javapoetParameterizedGeneratedTypeNameForBinding(binding));
    ImmutableList.Builder<CodeBlock> constructorInvocationParameters = ImmutableList.builder();

    boolean usesRawFrameworkTypes = false;
    UniqueNames fieldNames = new UniqueNames();
    for (Entry<BindingKey, FrameworkField> fieldEntry : fields.entrySet()) {
      BindingKey bindingKey = fieldEntry.getKey();
      FrameworkField bindingField = fieldEntry.getValue();

      // If the dependency type is not visible to this members injector, then use the raw framework
      // type for the field.
      boolean useRawFrameworkType =
          !VISIBLE_TO_MEMBERS_INJECTOR.visit(bindingKey.key().type(), binding);

      String fieldName = fieldNames.getUniqueName(bindingField.name());
      TypeName fieldType =
          useRawFrameworkType
              ? bindingField.javapoetFrameworkType().rawType
              : bindingField.javapoetFrameworkType();
      FieldSpec.Builder fieldBuilder = FieldSpec.builder(fieldType, fieldName, PRIVATE, FINAL);
      ParameterSpec.Builder parameterBuilder = ParameterSpec.builder(fieldType, fieldName);

      // If we're using the raw type for the field, then suppress the injectMembers method's
      // unchecked-type warning and the field's and the constructor and create-method's
      // parameters' raw-type warnings.
      if (useRawFrameworkType) {
        usesRawFrameworkTypes = true;
        fieldBuilder.addAnnotation(SUPPRESS_WARNINGS_RAWTYPES);
        parameterBuilder.addAnnotation(SUPPRESS_WARNINGS_RAWTYPES);
      }
      constructorBuilder.addParameter(parameterBuilder.build());
      createMethodBuilder.addParameter(parameterBuilder.build());

      FieldSpec field = fieldBuilder.build();
      injectorTypeBuilder.addField(field);
      constructorBuilder.addStatement("assert $N != null", field);
      constructorBuilder.addStatement("this.$N = $N", field, field);
      dependencyFieldsBuilder.put(bindingKey, field);
      constructorInvocationParameters.add(CodeBlocks.format("$N", field));
    }
    createMethodBuilder.addCode(CodeBlocks.join(constructorInvocationParameters.build(), ", "));
    createMethodBuilder.addCode(");");

    injectorTypeBuilder.addMethod(constructorBuilder.build());
    injectorTypeBuilder.addMethod(createMethodBuilder.build());

    Set<String> delegateMethods = new HashSet<>();
    ImmutableMap<BindingKey, FieldSpec> dependencyFields = dependencyFieldsBuilder.build();
    List<MethodSpec> injectMethodsForSubclasses = new ArrayList<>();
    for (InjectionSite injectionSite : binding.injectionSites()) {
      injectMembersBuilder.addCode(
          visibleToMembersInjector(binding, injectionSite.element())
              ? directInjectMemberCodeBlock(binding, dependencyFields, injectionSite)
              : delegateInjectMemberCodeBlock(dependencyFields, injectionSite));
      if (!injectionSite.element().getModifiers().contains(PUBLIC)
          && injectionSite.element().getEnclosingElement().equals(binding.bindingElement())
          && delegateMethods.add(injectionSiteDelegateMethodName(injectionSite.element()))) {
        injectMethodsForSubclasses.add(
            injectorMethodForSubclasses(
                dependencyFields,
                typeParameters,
                injectedTypeName,
                injectionSite.element(),
                injectionSite.dependencies()));
      }
    }

    if (usesRawFrameworkTypes) {
      injectMembersBuilder.addAnnotation(SUPPRESS_WARNINGS_UNCHECKED);
    }

    injectorTypeBuilder.addMethod(injectMembersBuilder.build());
    for (MethodSpec methodSpec : injectMethodsForSubclasses) {
      injectorTypeBuilder.addMethod(methodSpec);
    }

    return Optional.of(injectorTypeBuilder);
  }