Search in sources :

Example 86 with ParameterSpec

use of com.squareup.javapoet.ParameterSpec in project DaggerCodeParse-2.38.1base by hellogaod.

the class FactoryGenerator method getMethod.

private MethodSpec getMethod(ProvisionBinding binding) {
    UniqueNameSet uniqueFieldNames = new UniqueNameSet();
    ImmutableMap<DependencyRequest, FieldSpec> frameworkFields = frameworkFields(binding);
    frameworkFields.values().forEach(field -> uniqueFieldNames.claim(field.name));
    // AssistedInject注解修饰的构造函数,收集使用Assited修饰的参数
    Map<VariableElement, ParameterSpec> assistedParameters = assistedParameters(binding).stream().collect(toImmutableMap(element -> element, element -> ParameterSpec.builder(TypeName.get(element.asType()), uniqueFieldNames.getUniqueName(element.getSimpleName())).build()));
    // get方法
    // e.g. 使用Inject修饰的构造函数,这里会生成一个get(),无参,返回类型是构造函数所在类的类型
    TypeName providedTypeName = providedTypeName(binding);
    MethodSpec.Builder getMethod = methodBuilder("get").addModifiers(PUBLIC).returns(providedTypeName).addParameters(assistedParameters.values());
    // 如果没有使用AssistedInject注解修饰,那么get()方法还需要有Override注解修饰,表示重写
    if (factoryTypeName(binding).isPresent()) {
        getMethod.addAnnotation(Override.class);
    }
    CodeBlock invokeNewInstance = InjectionMethods.ProvisionMethod.invoke(binding, // 依赖kind决定使用CodeBlock代码块
    request -> frameworkTypeUsageStatement(CodeBlock.of("$N", frameworkFields.get(request)), request.kind()), // Assisted修饰的参数
    param -> assistedParameters.get(param).name, // 当前绑定bindingType决定绑定节点形成的新类名
    generatedClassNameForBinding(binding), // 实例化(如果需要的话,不需要则为空)当前绑定所在的module类
    moduleParameter(binding).map(module -> CodeBlock.of("$N", module)), compilerOptions, metadataUtil);
    if (binding.kind().equals(PROVISION)) {
        binding.nullableType().ifPresent(nullableType -> CodeBlocks.addAnnotation(getMethod, nullableType));
        getMethod.addStatement("return $L", invokeNewInstance);
    } else if (!binding.injectionSites().isEmpty()) {
        CodeBlock instance = CodeBlock.of("instance");
        getMethod.addStatement("$T $L = $L", providedTypeName, instance, invokeNewInstance).addCode(InjectionMethods.InjectionSiteMethod.invokeAll(// 当前绑定所在父类的所有使用Inject修饰的普通方法或变量
        binding.injectionSites(), // 当前绑定节点生成的类名
        generatedClassNameForBinding(binding), // instance
        instance, // 当前绑定(以Inject修饰构造函数为例)所在类的类型
        binding.key().type().java(), // 当前绑定的参数形成的Map<K,V>,K:当前参数依赖;V:当前参数依赖形成的变量根据当前kind依赖类型决定使用哪种架构类型包裹形成的代码块
        frameworkFieldUsages(binding.dependencies(), frameworkFields)::get, types, metadataUtil)).addStatement("return $L", instance);
    } else {
        getMethod.addStatement("return $L", invokeNewInstance);
    }
    return getMethod.build();
}
Also used : SINGLETON_INSTANCE(dagger.internal.codegen.binding.ContributionBinding.FactoryCreationStrategy.SINGLETON_INSTANCE) DELEGATE(dagger.internal.codegen.binding.ContributionBinding.FactoryCreationStrategy.DELEGATE) SourceFiles.generateBindingFieldsForDependencies(dagger.internal.codegen.binding.SourceFiles.generateBindingFieldsForDependencies) SourceFiles.generatedClassNameForBinding(dagger.internal.codegen.binding.SourceFiles.generatedClassNameForBinding) ClassName(com.squareup.javapoet.ClassName) Maps.transformValues(com.google.common.collect.Maps.transformValues) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) DependencyRequest(dagger.spi.model.DependencyRequest) INJECTION(dagger.spi.model.BindingKind.INJECTION) FINAL(javax.lang.model.element.Modifier.FINAL) Map(java.util.Map) DaggerTypes(dagger.internal.codegen.langmodel.DaggerTypes) ParameterSpec(com.squareup.javapoet.ParameterSpec) ImmutableMap(com.google.common.collect.ImmutableMap) DaggerStreams.toImmutableList(dagger.internal.codegen.extension.DaggerStreams.toImmutableList) MethodSpec.constructorBuilder(com.squareup.javapoet.MethodSpec.constructorBuilder) Element(javax.lang.model.element.Element) TypeNames.factoryOf(dagger.internal.codegen.javapoet.TypeNames.factoryOf) SourceVersion(javax.lang.model.SourceVersion) List(java.util.List) TypeName(com.squareup.javapoet.TypeName) Optional(java.util.Optional) SourceFiles.frameworkFieldUsages(dagger.internal.codegen.binding.SourceFiles.frameworkFieldUsages) KotlinMetadataUtil(dagger.internal.codegen.kotlin.KotlinMetadataUtil) SourceFileGenerator(dagger.internal.codegen.base.SourceFileGenerator) CodeBlocks(dagger.internal.codegen.javapoet.CodeBlocks) FieldSpec(com.squareup.javapoet.FieldSpec) GwtCompatibility.gwtIncompatibleAnnotation(dagger.internal.codegen.writing.GwtCompatibility.gwtIncompatibleAnnotation) VariableElement(javax.lang.model.element.VariableElement) ContributionBinding(dagger.internal.codegen.binding.ContributionBinding) AssistedInjectionAnnotations.assistedParameters(dagger.internal.codegen.binding.AssistedInjectionAnnotations.assistedParameters) SourceFiles.bindingTypeElementTypeVariableNames(dagger.internal.codegen.binding.SourceFiles.bindingTypeElementTypeVariableNames) Inject(javax.inject.Inject) DaggerElements(dagger.internal.codegen.langmodel.DaggerElements) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) XFiler(androidx.room.compiler.processing.XFiler) TypeSpec.classBuilder(com.squareup.javapoet.TypeSpec.classBuilder) BindingKind(dagger.spi.model.BindingKind) ProvisionBinding(dagger.internal.codegen.binding.ProvisionBinding) UNCHECKED(dagger.internal.codegen.javapoet.AnnotationSpecs.Suppression.UNCHECKED) CompilerOptions(dagger.internal.codegen.compileroption.CompilerOptions) CodeBlock(com.squareup.javapoet.CodeBlock) TypeVariableName(com.squareup.javapoet.TypeVariableName) DaggerStreams.toImmutableMap(dagger.internal.codegen.extension.DaggerStreams.toImmutableMap) RAWTYPES(dagger.internal.codegen.javapoet.AnnotationSpecs.Suppression.RAWTYPES) PRIVATE(javax.lang.model.element.Modifier.PRIVATE) MethodSpec(com.squareup.javapoet.MethodSpec) SourceFiles.frameworkTypeUsageStatement(dagger.internal.codegen.binding.SourceFiles.frameworkTypeUsageStatement) SourceFiles.parameterizedGeneratedTypeNameForBinding(dagger.internal.codegen.binding.SourceFiles.parameterizedGeneratedTypeNameForBinding) PUBLIC(javax.lang.model.element.Modifier.PUBLIC) TypeSpec(com.squareup.javapoet.TypeSpec) Binding(dagger.internal.codegen.binding.Binding) TypeParameterElement(javax.lang.model.element.TypeParameterElement) PROVISION(dagger.spi.model.BindingKind.PROVISION) STATIC(javax.lang.model.element.Modifier.STATIC) UniqueNameSet(dagger.internal.codegen.base.UniqueNameSet) CodeBlocks.makeParametersCodeBlock(dagger.internal.codegen.javapoet.CodeBlocks.makeParametersCodeBlock) MethodSpec.methodBuilder(com.squareup.javapoet.MethodSpec.methodBuilder) AnnotationSpecs.suppressWarnings(dagger.internal.codegen.javapoet.AnnotationSpecs.suppressWarnings) ASSISTED_INJECTION(dagger.spi.model.BindingKind.ASSISTED_INJECTION) Factory(dagger.internal.Factory) UniqueNameSet(dagger.internal.codegen.base.UniqueNameSet) TypeName(com.squareup.javapoet.TypeName) DependencyRequest(dagger.spi.model.DependencyRequest) ParameterSpec(com.squareup.javapoet.ParameterSpec) MethodSpec(com.squareup.javapoet.MethodSpec) CodeBlock(com.squareup.javapoet.CodeBlock) CodeBlocks.makeParametersCodeBlock(dagger.internal.codegen.javapoet.CodeBlocks.makeParametersCodeBlock) VariableElement(javax.lang.model.element.VariableElement) FieldSpec(com.squareup.javapoet.FieldSpec)

Example 87 with ParameterSpec

use of com.squareup.javapoet.ParameterSpec in project pnc by project-ncl.

the class PatchDtoGenerator method createAddMethod.

private void createAddMethod(List<MethodSpec> methods, VariableElement dtoField, String patchBuilderClassName) {
    String fieldName = dtoField.getSimpleName().toString();
    String methodName = "add" + StringUtils.firstCharToUpperCase(fieldName);
    MethodSpec.Builder methodBuilder = beginMethod(methodName);
    ParameterSpec parameterSpec = ParameterSpec.builder(ParameterizedTypeName.get(dtoField.asType()), "elements").build();
    methodBuilder.addParameter(parameterSpec);
    methodBuilder.returns(ClassName.get("org.jboss.pnc.client.patch", patchBuilderClassName));
    methodBuilder.addStatement("return add(elements, \"" + fieldName + "\")");
    MethodSpec methodSpec = completeMethod(methodBuilder);
    methods.add(methodSpec);
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) ParameterSpec(com.squareup.javapoet.ParameterSpec)

Example 88 with ParameterSpec

use of com.squareup.javapoet.ParameterSpec in project pnc by project-ncl.

the class PatchDtoGenerator method createRemoveMethod.

private void createRemoveMethod(List<MethodSpec> methods, VariableElement dtoField, String patchBuilderClassName) {
    String fieldName = dtoField.getSimpleName().toString();
    String methodName = "remove" + StringUtils.firstCharToUpperCase(fieldName);
    MethodSpec.Builder methodBuilder = beginMethod(methodName);
    ParameterSpec parameterSpec = ParameterSpec.builder(ParameterizedTypeName.get(ClassName.get(Collection.class), TypeName.get(Object.class)), "keys").build();
    methodBuilder.addParameter(parameterSpec);
    methodBuilder.returns(ClassName.get("org.jboss.pnc.client.patch", patchBuilderClassName));
    methodBuilder.addStatement("return remove(keys, \"" + fieldName + "\")");
    MethodSpec methodSpec = completeMethod(methodBuilder);
    methods.add(methodSpec);
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) ParameterSpec(com.squareup.javapoet.ParameterSpec) Collection(java.util.Collection)

Example 89 with ParameterSpec

use of com.squareup.javapoet.ParameterSpec in project safe-logging by palantir.

the class LoggerGenerator method createLoggerBridge.

private static TypeSpec createLoggerBridge() {
    TypeSpec.Builder bridgeBuilder = TypeSpec.interfaceBuilder(BRIDGE_NAME).addModifiers(Modifier.PUBLIC).addJavadoc("Logger bridge which must be implemented by frameworks which implement the safe-logging " + "facade API.\nMethods should only be called by the safe-logger implementation, the bridge " + "is not meant to be used directly.").addAnnotation(AnnotationSpec.builder(Generated.class).addMember("value", "$S", LoggerGenerator.class.getName()).build()).addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "TooManyArguments").build());
    for (LoggerLevel level : LoggerLevel.values()) {
        bridgeBuilder.addMethod(MethodSpec.methodBuilder(level.isEnabled()).addJavadoc("Returns {@code true} if the {@code $L} level is enabled.", level.lower()).addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT).returns(boolean.class).build());
        ParameterSpec messageParameter = ParameterSpec.builder(String.class, "message").addAnnotation(CompileTimeConstant.class).addJavadoc("Message string to log, supports slf4j-style curly-brace interpolation\n").build();
        ParameterSpec throwableParameter = ParameterSpec.builder(THROWABLE_TYPE, THROWABLE_NAME).addJavadoc("Throwable to log with a stack trace\n").addAnnotation(Nullable.class).build();
        for (int i = 0; i <= 10; i++) {
            MethodSpec.Builder builder = MethodSpec.methodBuilder(level.lower()).addJavadoc("Logs the provided parameters at {@code $L} level.", level.lower()).addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT).addParameter(messageParameter);
            for (int j = 0; j < i; j++) {
                builder.addParameter(ParameterSpec.builder(ARG_TYPE, "arg" + j).build());
            }
            MethodSpec spec = builder.build();
            MethodSpec specWithThrowable = spec.toBuilder().addParameter(throwableParameter).build();
            bridgeBuilder.addMethod(spec).addMethod(specWithThrowable);
        }
        MethodSpec spec = MethodSpec.methodBuilder(level.lower()).addJavadoc("Logs the provided parameters at {@code $L} level.", level.lower()).addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT).addParameter(messageParameter).addParameter(ParameterSpec.builder(ARGS_LIST_TYPE, "args").addJavadoc("List of safe-loggable arguments associated with this event\n").build()).build();
        MethodSpec specWithThrowable = spec.toBuilder().addParameter(throwableParameter).build();
        bridgeBuilder.addMethod(spec).addMethod(specWithThrowable);
    }
    return bridgeBuilder.build();
}
Also used : ParameterSpec(com.squareup.javapoet.ParameterSpec) MethodSpec(com.squareup.javapoet.MethodSpec) Nullable(javax.annotation.Nullable) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 90 with ParameterSpec

use of com.squareup.javapoet.ParameterSpec in project DaggerCodeParse-2.38.1base by hellogaod.

the class OptionalFactories method presentOptionalFactoryClass.

private TypeSpec presentOptionalFactoryClass(PresentFactorySpec spec) {
    FieldSpec delegateField = FieldSpec.builder(spec.delegateType(), "delegate", PRIVATE, FINAL).build();
    ParameterSpec delegateParameter = ParameterSpec.builder(delegateField.type, "delegate").build();
    TypeSpec.Builder factoryClassBuilder = classBuilder(spec.factoryClassName()).addTypeVariable(spec.typeVariable()).addModifiers(PRIVATE, STATIC, FINAL).addJavadoc("A {@code $T} that uses a delegate {@code $T}.", spec.factoryType(), delegateField.type);
    spec.superclass().ifPresent(factoryClassBuilder::superclass);
    spec.superinterface().ifPresent(factoryClassBuilder::addSuperinterface);
    return factoryClassBuilder.addField(delegateField).addMethod(constructorBuilder().addModifiers(PRIVATE).addParameter(delegateParameter).addCode("this.$N = $T.checkNotNull($N);", delegateField, Preconditions.class, delegateParameter).build()).addMethod(presentOptionalFactoryGetMethod(spec, delegateField)).addMethod(methodBuilder("of").addModifiers(PRIVATE, STATIC).addTypeVariable(spec.typeVariable()).returns(spec.factoryType()).addParameter(delegateParameter).addCode("return new $L<$T>($N);", spec.factoryClassName(), spec.typeVariable(), delegateParameter).build()).build();
}
Also used : ParameterSpec(com.squareup.javapoet.ParameterSpec) Preconditions(dagger.internal.Preconditions) FieldSpec(com.squareup.javapoet.FieldSpec) TypeSpec(com.squareup.javapoet.TypeSpec)

Aggregations

ParameterSpec (com.squareup.javapoet.ParameterSpec)97 MethodSpec (com.squareup.javapoet.MethodSpec)59 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)40 ArrayList (java.util.ArrayList)34 TypeName (com.squareup.javapoet.TypeName)30 ClassName (com.squareup.javapoet.ClassName)27 TypeSpec (com.squareup.javapoet.TypeSpec)26 Map (java.util.Map)26 CodeBlock (com.squareup.javapoet.CodeBlock)23 FieldSpec (com.squareup.javapoet.FieldSpec)22 List (java.util.List)20 HashMap (java.util.HashMap)18 AnnotationSpec (com.squareup.javapoet.AnnotationSpec)17 JavaFile (com.squareup.javapoet.JavaFile)13 Modifier (javax.lang.model.element.Modifier)13 TypeElement (javax.lang.model.element.TypeElement)13 Collectors (java.util.stream.Collectors)12 IOException (java.io.IOException)11 Element (javax.lang.model.element.Element)11 TypeMirror (javax.lang.model.type.TypeMirror)11