Search in sources :

Example 31 with JavaFile

use of com.squareup.javapoet.JavaFile in project tiger by google.

the class NewInjectorGenerator method generateAll.

private void generateAll() {
    for (ComponentInfo component : orderedComponents) {
        Set<ClassName> injected = new HashSet<>();
        Set<TypeElement> allMembersInjectors = Sets.newHashSet(memberInjectors.get(component));
        while (!allMembersInjectors.isEmpty()) {
            TypeElement injector = Iterables.getFirst(allMembersInjectors, null);
            Preconditions.checkNotNull(injector, String.format("Empty allMembersInjector."));
            allMembersInjectors.remove(injector);
            for (TypeMirror parentInterface : injector.getInterfaces()) {
                allMembersInjectors.add((TypeElement) ((DeclaredType) parentInterface).asElement());
            }
            for (Element method : injector.getEnclosedElements()) {
                if (Utils.isInjectionMethod(method)) {
                    VariableElement var = Iterables.getOnlyElement(((ExecutableElement) method).getParameters());
                    if (var.asType().getKind().equals(TypeKind.TYPEVAR)) {
                        // TODO(freeman): support generic injection method.
                        continue;
                    }
                    TypeElement varTypeElement = (TypeElement) ((DeclaredType) var.asType()).asElement();
                    if (!injected.add(ClassName.get(varTypeElement))) {
                        continue;
                    }
                    generateInjectionMethod(varTypeElement, component.getScope());
                } else if (Utils.isProvisionMethodInInjector(method)) {
                    generateProvisionMethodIfNeeded(Utils.getKeyProvidedByMethod((ExecutableElement) method), injector);
                } else {
                    messager.printMessage(Kind.WARNING, String.format("Unknown element %s from injector %s.", method, injector));
                }
            }
        }
    }
    for (ComponentInfo component : orderedComponents) {
        if (componentTree.get(component) == null) {
            continue;
        }
        for (Map.Entry<ClassName, TypeSpec.Builder> entry : packagedInjectorBuilders.entrySet()) {
            ClassName packagedInjectorClassName = entry.getKey();
            if (!component.equals(getComponentFromPackagedInjectorClassName(packagedInjectorClassName))) {
                continue;
            }
            generateInheritedProvisionMethods(packagedInjectorClassName);
        }
    }
    for (ComponentInfo component : orderedComponents) {
        if (componentTree.get(component) == null) {
            continue;
        }
        for (Map.Entry<ClassName, TypeSpec.Builder> entry : packagedInjectorBuilders.entrySet()) {
            ClassName packagedInjectorClassName = entry.getKey();
            if (!component.equals(getComponentFromPackagedInjectorClassName(packagedInjectorClassName))) {
                continue;
            }
            generateInheritedInjectionMethods(packagedInjectorClassName);
        }
    }
    for (Map.Entry<ClassName, TypeSpec.Builder> entry : packagedInjectorBuilders.entrySet()) {
        String packageString = entry.getKey().packageName();
        TypeSpec.Builder builder = entry.getValue();
        JavaFile javaFile = JavaFile.builder(packageString, builder.build()).build();
        // messager.printMessage(Kind.NOTE, String.format("java file: %s", javaFile));
        try {
            javaFile.writeTo(processingEnv.getFiler());
        } catch (IOException e) {
            Throwables.propagate(e);
        }
    }
    generateTopLevelInjectors();
}
Also used : TypeElement(javax.lang.model.element.TypeElement) PackageElement(javax.lang.model.element.PackageElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) Builder(com.squareup.javapoet.TypeSpec.Builder) VariableElement(javax.lang.model.element.VariableElement) IOException(java.io.IOException) TypeMirror(javax.lang.model.type.TypeMirror) Builder(com.squareup.javapoet.TypeSpec.Builder) ClassName(com.squareup.javapoet.ClassName) JavaFile(com.squareup.javapoet.JavaFile) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet) DeclaredType(javax.lang.model.type.DeclaredType) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 32 with JavaFile

use of com.squareup.javapoet.JavaFile in project tiger by google.

the class SubcomponentParentInterfaceGenerator method generate.

public void generate(TypeElement subcomponent, Map<TypeElement, TypeElement> componentToParentMap) {
    ExtraDependenciesOnParentCalculator extraDependenciesOnParentCalculator = ExtraDependenciesOnParentCalculator.getInstance(componentToParentMap, processingEnv, utils);
    TypeSpec.Builder interfaceBuilder = TypeSpec.interfaceBuilder(getInterfaceName(subcomponent, utils)).addAnnotation(AnnotationSpec.builder(Generated.class).addMember("value", "$S", GENERATOR_NAME).build()).addModifiers(Modifier.PUBLIC);
    Set<BindingKey> done = new HashSet<>();
    for (BindingKey i : extraDependenciesOnParentCalculator.calculate(subcomponent, null)) {
        utils.generateAbstractProvisonMethodIfNeeded(interfaceBuilder, utils.getProvisionMethodName(i), i, done);
    }
    JavaFile javaFile = JavaFile.builder(utils.getPackageString(subcomponent), interfaceBuilder.build()).build();
    logger.n("SubcomponentParentInterface package: %s, toString: %s", javaFile.packageName, javaFile.toString());
    try {
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : JavaFile(com.squareup.javapoet.JavaFile) IOException(java.io.IOException) TypeSpec(com.squareup.javapoet.TypeSpec) HashSet(java.util.HashSet)

Example 33 with JavaFile

use of com.squareup.javapoet.JavaFile in project tiger by google.

the class TigerDaggerGeneratorProcessor method generateWrapperComponents.

/**
 * Generates Dagger component implementations that wrap around the core injectors.
 */
private void generateWrapperComponents(Set<TypeElement> components) {
    componentToBuilderMap = collectComponentToBuilderMap();
    for (TypeElement component : components) {
        CoreInjectorInfo coreInjector = componentToCoreInjectorMap.get(component);
        // Ignore orphan components whose core injector is not generated.
        if (scopeSizer.getScopeSize(coreInjector) == -1) {
            continue;
        }
        ClassName coreInjectorClassName = getCoreInejectorClassName(coreInjectorPackage, coreInjector);
        String packageString = utils.getPackageString(component);
        String generatedComponentSimpleName = utils.getComponentImplementationSimpleNameFromInterface(component);
        messager.printMessage(Kind.NOTE, TAG + ".generateWrapperComponents: generated component " + generatedComponentSimpleName);
        TypeSpec.Builder componentBuilder = TypeSpec.classBuilder(generatedComponentSimpleName).addModifiers(Modifier.PUBLIC).addSuperinterface(TypeName.get(component.asType())).superclass(coreInjectorClassName);
        // Ctor with parent component, component dependencies and modules as parameters.
        MethodSpec.Builder ctorBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE);
        // Ctor parent component
        TypeElement parentComponent = componentToParentMap.get(component);
        StringBuilder callSuperStringBuilder = new StringBuilder("super(");
        boolean needLeadingComma = false;
        if (parentComponent != null) {
            needLeadingComma = true;
            ctorBuilder.addParameter(TypeName.get(parentComponent.asType()), utils.getSourceCodeName(parentComponent));
            // Cast the interface to implement which is a subclass of core injector therefore will be
            // accept by compiler.
            callSuperStringBuilder.append("($T) ").append(utils.getSourceCodeName(parentComponent));
        }
        // Ctor component dependencies parameters
        if (!coreInjectorToComponentDependencyMap.get(coreInjector).isEmpty()) {
            if (needLeadingComma) {
                callSuperStringBuilder.append(", ");
            }
            needLeadingComma = true;
            Set<TypeElement> deps = componentToComponentDependencyMap.get(component);
            for (TypeElement typeElement : utils.sortByFullName(coreInjectorToComponentDependencyMap.get(coreInjector))) {
                if (deps.contains(typeElement)) {
                    ctorBuilder.addParameter(TypeName.get(typeElement.asType()), utils.getSourceCodeName(typeElement));
                    callSuperStringBuilder.append(utils.getSourceCodeName(typeElement));
                } else {
                    callSuperStringBuilder.append("null");
                }
                callSuperStringBuilder.append(", ");
            }
            callSuperStringBuilder.delete(callSuperStringBuilder.length() - 2, callSuperStringBuilder.length());
        }
        // Ctor @BindsInstance parameters
        if (!coreInjectorToBindsInstanceMap.get(coreInjector).isEmpty()) {
            if (needLeadingComma) {
                callSuperStringBuilder.append(", ");
            }
            needLeadingComma = true;
            Set<BindingKey> bindsInstances = componentToBindsInstanceMap.get(component);
            for (BindingKey key : utils.sortBindingKeys(coreInjectorToBindsInstanceMap.get(coreInjector))) {
                if (bindsInstances.contains(key)) {
                    String sourceCodeName = utils.getSourceCodeNameHandlingBox(key, dependencies);
                    ctorBuilder.addParameter(key.getTypeName(), sourceCodeName);
                    callSuperStringBuilder.append(sourceCodeName);
                } else {
                    callSuperStringBuilder.append("null");
                }
                callSuperStringBuilder.append(", ");
            }
            callSuperStringBuilder.delete(callSuperStringBuilder.length() - 2, callSuperStringBuilder.length());
        }
        // Ctor module parameters
        Set<TypeElement> allComponentModules = getAllModulesOfComponentRecursively(component);
        List<TypeElement> sortedComponentPassedModules = utils.sortByFullName(utils.getNonNullaryCtorOnes(allComponentModules));
        Set<TypeElement> coreInjectorPassedModules = new HashSet<>();
        coreInjectorPassedModules.addAll(scopedPassedModules.get(coreInjector));
        coreInjectorPassedModules.addAll(unscopedPassedModules);
        List<TypeElement> sortedCoreInjectorPassedModules = utils.sortByFullName(coreInjectorPassedModules);
        if (!sortedCoreInjectorPassedModules.isEmpty()) {
            if (needLeadingComma) {
                callSuperStringBuilder.append(", ");
            }
            needLeadingComma = true;
            for (TypeElement typeElement : sortedCoreInjectorPassedModules) {
                if (sortedComponentPassedModules.contains(typeElement)) {
                    ctorBuilder.addParameter(TypeName.get(typeElement.asType()), utils.getSourceCodeName(typeElement));
                    callSuperStringBuilder.append(utils.getSourceCodeName(typeElement));
                } else {
                    callSuperStringBuilder.append("null");
                }
                callSuperStringBuilder.append(", ");
            }
            callSuperStringBuilder.delete(callSuperStringBuilder.length() - 2, callSuperStringBuilder.length());
        }
        callSuperStringBuilder.append(");");
        if (parentComponent != null) {
            CoreInjectorInfo coreInjectorInfo = componentToCoreInjectorMap.get(parentComponent);
            ctorBuilder.addCode(callSuperStringBuilder.toString(), // TODO: hack, restore
            getCoreInejectorClassName(coreInjectorPackage, coreInjectorInfo));
        // ClassName.get(
        // utils.getPackageString(parentComponent),
        // utils.getComponentImplementationSimpleNameFromInterface(parentComponent)));
        } else {
            ctorBuilder.addCode(callSuperStringBuilder.toString());
        }
        componentBuilder.addMethod(ctorBuilder.build());
        // Generate provision method
        // Generate Builder.
        @Nullable TypeElement explicitBuilder = componentToBuilderMap.get(component);
        generateWrapperComponentBuilder(component, parentComponent, sortedComponentPassedModules, componentBuilder, coreInjector, explicitBuilder);
        // Generate builder().
        ClassName builderClassName = ClassName.get(packageString, generatedComponentSimpleName, explicitBuilder != null ? explicitBuilder.getSimpleName().toString() : "Builder");
        MethodSpec.Builder builderMethodSpecBuilder = MethodSpec.methodBuilder("builder").addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(builderClassName);
        boolean isSubcomponent = utils.isSubcomponent(component);
        if (isSubcomponent) {
            builderMethodSpecBuilder.addParameter(ClassName.get(componentToParentMap.get(component).asType()), "v");
        }
        builderMethodSpecBuilder.addCode("return new $T($L);", builderClassName, isSubcomponent ? "v" : "");
        componentBuilder.addMethod(builderMethodSpecBuilder.build());
        JavaFile javaFile = JavaFile.builder(packageString, componentBuilder.build()).build();
        try {
            messager.printMessage(Kind.NOTE, String.format("%s: writing java file: %s", TAG, javaFile.toJavaFileObject().getName()));
            javaFile.writeTo(processingEnv.getFiler());
        } catch (IOException e) {
        // messager.printMessage(Kind.ERROR, e.toString());
        }
    }
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) IOException(java.io.IOException) ClassName(com.squareup.javapoet.ClassName) JavaFile(com.squareup.javapoet.JavaFile) Nullable(javax.annotation.Nullable) TypeSpec(com.squareup.javapoet.TypeSpec) HashSet(java.util.HashSet)

Example 34 with JavaFile

use of com.squareup.javapoet.JavaFile in project dagger by square.

the class InjectAdapterProcessor method generateInjectAdapter.

/**
 * Write a companion class for {@code type} that extends {@link Binding}.
 *
 * @param constructor the injectable constructor, or null if this binding
 *     supports members injection only.
 */
private void generateInjectAdapter(TypeElement type, ExecutableElement constructor, List<Element> fields) throws IOException {
    String packageName = getPackage(type).getQualifiedName().toString();
    TypeMirror supertype = getApplicationSupertype(type);
    if (supertype != null) {
        supertype = processingEnv.getTypeUtils().erasure(supertype);
    }
    ClassName injectedClassName = ClassName.get(type);
    ClassName adapterClassName = adapterName(injectedClassName, INJECT_ADAPTER_SUFFIX);
    boolean isAbstract = type.getModifiers().contains(ABSTRACT);
    boolean injectMembers = !fields.isEmpty() || supertype != null;
    boolean disambiguateFields = !fields.isEmpty() && (constructor != null) && !constructor.getParameters().isEmpty();
    boolean dependent = injectMembers || ((constructor != null) && !constructor.getParameters().isEmpty());
    TypeSpec.Builder result = TypeSpec.classBuilder(adapterClassName.simpleName()).addOriginatingElement(type).addModifiers(PUBLIC, FINAL).superclass(ParameterizedTypeName.get(ClassName.get(Binding.class), injectedClassName)).addJavadoc("$L", bindingTypeDocs(injectableType(type.asType()), isAbstract, injectMembers, dependent).toString());
    for (Element field : fields) {
        result.addField(memberBindingField(disambiguateFields, field));
    }
    if (constructor != null) {
        for (VariableElement parameter : constructor.getParameters()) {
            result.addField(parameterBindingField(disambiguateFields, parameter));
        }
    }
    if (supertype != null) {
        result.addField(supertypeBindingField(supertype));
    }
    result.addMethod(writeInjectAdapterConstructor(constructor, type, injectedClassName));
    if (dependent) {
        result.addMethod(attachMethod(constructor, fields, disambiguateFields, injectedClassName, supertype, true));
        result.addMethod(getDependenciesMethod(constructor, fields, disambiguateFields, supertype, true));
    }
    if (constructor != null) {
        result.addMethod(getMethod(constructor, disambiguateFields, injectMembers, injectedClassName));
    }
    if (injectMembers) {
        result.addMethod(membersInjectMethod(fields, disambiguateFields, injectedClassName, supertype));
    }
    JavaFile javaFile = JavaFile.builder(packageName, result.build()).addFileComment(AdapterJavadocs.GENERATED_BY_DAGGER).build();
    javaFile.writeTo(processingEnv.getFiler());
}
Also used : Binding(dagger.internal.Binding) TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) ClassName(com.squareup.javapoet.ClassName) JavaFile(com.squareup.javapoet.JavaFile) Util.rawTypeToString(dagger.internal.codegen.Util.rawTypeToString) Util.elementToString(dagger.internal.codegen.Util.elementToString) VariableElement(javax.lang.model.element.VariableElement) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 35 with JavaFile

use of com.squareup.javapoet.JavaFile in project T-MVP by north2016.

the class InstanceProcessor method process.

@Override
public void process(RoundEnvironment roundEnv, AnnotationProcessor mAbstractProcessor) {
    String CLASS_NAME = "InstanceFactory";
    TypeSpec.Builder tb = classBuilder(CLASS_NAME).addModifiers(PUBLIC, FINAL).addJavadoc("@ 实例化工厂 此类由apt自动生成");
    MethodSpec.Builder methodBuilder1 = MethodSpec.methodBuilder("create").addAnnotation(MemoryCache.class).addJavadoc("@此方法由apt自动生成").returns(Object.class).addModifiers(PUBLIC, STATIC).addException(IllegalAccessException.class).addException(InstantiationException.class).addParameter(Class.class, "mClass");
    List<ClassName> mList = new ArrayList<>();
    CodeBlock.Builder blockBuilder = CodeBlock.builder();
    // 括号开始
    blockBuilder.beginControlFlow(" switch (mClass.getSimpleName())");
    try {
        for (TypeElement element : ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(InstanceFactory.class))) {
            mAbstractProcessor.mMessager.printMessage(Diagnostic.Kind.NOTE, "正在处理: " + element.toString());
            if (!Utils.isValidClass(mAbstractProcessor.mMessager, element))
                return;
            ClassName currentType = ClassName.get(element);
            if (mList.contains(currentType))
                continue;
            mList.add(currentType);
            // String className = null;
            // try {
            // Class<?> clazz = element.getAnnotation(InstanceFactory.class).value();
            // className = clazz.getCanonicalName();
            // } catch (MirroredTypeException mte) {
            // DeclaredType classTypeMirror = (DeclaredType) mte.getTypeMirror();
            // TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();
            // className = classTypeElement.getQualifiedName().toString();
            // } catch (Exception e) {
            // }
            // if (className != null && !className.equals(InstanceFactory.class.getName())) {
            // blockBuilder.addStatement("case $S: return  new $T()", currentType.simpleName(), Utils.getType(className));//初始化Repository
            // } else {
            // 初始化Presenter
            blockBuilder.addStatement("case $S: return  new $T()", currentType.simpleName(), currentType);
        // }
        }
        blockBuilder.addStatement("default: return mClass.newInstance()");
        blockBuilder.endControlFlow();
        methodBuilder1.addCode(blockBuilder.build());
        tb.addMethod(methodBuilder1.build());
        // 生成源代码
        JavaFile javaFile = JavaFile.builder(Utils.PackageName, tb.build()).build();
        // 在 app module/build/generated/source/apt 生成一份源代码
        javaFile.writeTo(mAbstractProcessor.mFiler);
    } catch (FilerException e) {
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) ArrayList(java.util.ArrayList) CodeBlock(com.squareup.javapoet.CodeBlock) IOException(java.io.IOException) IOException(java.io.IOException) FilerException(javax.annotation.processing.FilerException) InstanceFactory(com.app.annotation.apt.InstanceFactory) ClassName(com.squareup.javapoet.ClassName) JavaFile(com.squareup.javapoet.JavaFile) FilerException(javax.annotation.processing.FilerException) TypeSpec(com.squareup.javapoet.TypeSpec)

Aggregations

JavaFile (com.squareup.javapoet.JavaFile)68 TypeSpec (com.squareup.javapoet.TypeSpec)43 IOException (java.io.IOException)42 TypeElement (javax.lang.model.element.TypeElement)25 MethodSpec (com.squareup.javapoet.MethodSpec)21 ClassName (com.squareup.javapoet.ClassName)19 Element (javax.lang.model.element.Element)15 ExecutableElement (javax.lang.model.element.ExecutableElement)12 HashMap (java.util.HashMap)10 File (java.io.File)9 HashSet (java.util.HashSet)9 Map (java.util.Map)9 VariableElement (javax.lang.model.element.VariableElement)9 Builder (com.squareup.javapoet.TypeSpec.Builder)8 ArrayList (java.util.ArrayList)8 ProcessorException (com.github.mvp4g.mvp4g2.processor.ProcessorException)6 PackageElement (javax.lang.model.element.PackageElement)6 DeclaredType (javax.lang.model.type.DeclaredType)6 TypeMirror (javax.lang.model.type.TypeMirror)6 CodeBlock (com.squareup.javapoet.CodeBlock)5