Search in sources :

Example 96 with ClassName

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

the class ModuleAdapterProcessor method generateProvidesAdapter.

private TypeSpec generateProvidesAdapter(ClassName moduleClassName, ClassName adapterName, ExecutableElement providerMethod, Map<ExecutableElement, ClassName> methodToClassName, Map<String, AtomicInteger> methodNameToNextId, boolean library) {
    String methodName = providerMethod.getSimpleName().toString();
    TypeMirror moduleType = providerMethod.getEnclosingElement().asType();
    ClassName className = bindingClassName(adapterName, providerMethod, methodToClassName, methodNameToNextId);
    TypeName returnType = Util.injectableType(providerMethod.getReturnType());
    List<? extends VariableElement> parameters = providerMethod.getParameters();
    boolean dependent = !parameters.isEmpty();
    TypeSpec.Builder result = TypeSpec.classBuilder(className.simpleName()).addJavadoc("$L", bindingTypeDocs(returnType, false, false, dependent)).addModifiers(PUBLIC, STATIC, FINAL).superclass(ParameterizedTypeName.get(ClassName.get(ProvidesBinding.class), returnType));
    result.addField(moduleClassName, "module", PRIVATE, FINAL);
    for (Element parameter : parameters) {
        result.addField(bindingOf(parameter.asType()), parameterName(parameter), PRIVATE);
    }
    boolean singleton = providerMethod.getAnnotation(Singleton.class) != null;
    String key = GeneratorKeys.get(providerMethod);
    result.addMethod(MethodSpec.constructorBuilder().addModifiers(PUBLIC).addParameter(moduleClassName, "module").addStatement("super($S, $L, $S, $S)", key, (singleton ? "IS_SINGLETON" : "NOT_SINGLETON"), typeToString(moduleType), methodName).addStatement("this.module = module").addStatement("setLibrary($L)", library).build());
    if (dependent) {
        MethodSpec.Builder attachBuilder = MethodSpec.methodBuilder("attach").addJavadoc(AdapterJavadocs.ATTACH_METHOD).addAnnotation(Override.class).addAnnotation(Util.UNCHECKED).addModifiers(PUBLIC).addParameter(Linker.class, "linker");
        for (VariableElement parameter : parameters) {
            String parameterKey = GeneratorKeys.get(parameter);
            attachBuilder.addStatement("$N = ($T) linker.requestBinding($S, $T.class, getClass().getClassLoader())", parameterName(parameter), bindingOf(parameter.asType()), parameterKey, moduleClassName);
        }
        result.addMethod(attachBuilder.build());
        MethodSpec.Builder getDependenciesBuilder = MethodSpec.methodBuilder("getDependencies").addJavadoc(AdapterJavadocs.GET_DEPENDENCIES_METHOD).addAnnotation(Override.class).addModifiers(PUBLIC).addParameter(Util.SET_OF_BINDINGS, "getBindings").addParameter(Util.SET_OF_BINDINGS, "injectMembersBindings");
        for (Element parameter : parameters) {
            getDependenciesBuilder.addStatement("getBindings.add($N)", parameterName(parameter));
        }
        result.addMethod(getDependenciesBuilder.build());
    }
    MethodSpec.Builder getBuilder = MethodSpec.methodBuilder("get").addJavadoc(AdapterJavadocs.GET_METHOD, returnType).addAnnotation(Override.class).addModifiers(PUBLIC).returns(returnType).addCode("return module.$N(", methodName);
    boolean first = true;
    for (Element parameter : parameters) {
        if (!first)
            getBuilder.addCode(", ");
        getBuilder.addCode("$N.get()", parameterName(parameter));
        first = false;
    }
    getBuilder.addCode(");\n");
    result.addMethod(getBuilder.build());
    return result.build();
}
Also used : TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) VariableElement(javax.lang.model.element.VariableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Util.typeToString(dagger.internal.codegen.Util.typeToString) Util.elementToString(dagger.internal.codegen.Util.elementToString) VariableElement(javax.lang.model.element.VariableElement) TypeMirror(javax.lang.model.type.TypeMirror) Singleton(javax.inject.Singleton) ClassName(com.squareup.javapoet.ClassName) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 97 with ClassName

use of com.squareup.javapoet.ClassName in project ActivityRouter by mzule.

the class RouterProcessor method handleRouter.

private boolean handleRouter(String genClassName, RoundEnvironment roundEnv) {
    Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(Router.class);
    MethodSpec.Builder mapMethod = MethodSpec.methodBuilder("map").addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC).addStatement("java.util.Map<String,String> transfer = null").addStatement("com.github.mzule.activityrouter.router.ExtraTypes extraTypes").addCode("\n");
    for (Element element : elements) {
        Router router = element.getAnnotation(Router.class);
        String[] transfer = router.transfer();
        if (transfer.length > 0 && !"".equals(transfer[0])) {
            mapMethod.addStatement("transfer = new java.util.HashMap<String, String>()");
            for (String s : transfer) {
                String[] components = s.split("=>");
                if (components.length != 2) {
                    error("transfer `" + s + "` not match a=>b format");
                    break;
                }
                mapMethod.addStatement("transfer.put($S, $S)", components[0], components[1]);
            }
        } else {
            mapMethod.addStatement("transfer = null");
        }
        mapMethod.addStatement("extraTypes = new com.github.mzule.activityrouter.router.ExtraTypes()");
        mapMethod.addStatement("extraTypes.setTransfer(transfer)");
        addStatement(mapMethod, int.class, router.intParams());
        addStatement(mapMethod, long.class, router.longParams());
        addStatement(mapMethod, boolean.class, router.booleanParams());
        addStatement(mapMethod, short.class, router.shortParams());
        addStatement(mapMethod, float.class, router.floatParams());
        addStatement(mapMethod, double.class, router.doubleParams());
        addStatement(mapMethod, byte.class, router.byteParams());
        addStatement(mapMethod, char.class, router.charParams());
        for (String format : router.value()) {
            ClassName className;
            Name methodName = null;
            if (element.getKind() == ElementKind.CLASS) {
                className = ClassName.get((TypeElement) element);
            } else if (element.getKind() == ElementKind.METHOD) {
                className = ClassName.get((TypeElement) element.getEnclosingElement());
                methodName = element.getSimpleName();
            } else {
                throw new IllegalArgumentException("unknow type");
            }
            if (format.startsWith("/")) {
                error("Router#value can not start with '/'. at [" + className + "]@Router(\"" + format + "\")");
                return false;
            }
            if (format.endsWith("/")) {
                error("Router#value can not end with '/'. at [" + className + "]@Router(\"" + format + "\")");
                return false;
            }
            if (element.getKind() == ElementKind.CLASS) {
                mapMethod.addStatement("com.github.mzule.activityrouter.router.Routers.map($S, $T.class, null, extraTypes)", format, className);
            } else {
                mapMethod.addStatement("com.github.mzule.activityrouter.router.Routers.map($S, null, " + "new MethodInvoker() {\n" + "   public void invoke(android.content.Context context, android.os.Bundle bundle) {\n" + "       $T.$N(context, bundle);\n" + "   }\n" + "}, " + "extraTypes)", format, className, methodName);
            }
        }
        mapMethod.addCode("\n");
    }
    TypeSpec routerMapping = TypeSpec.classBuilder(genClassName).addModifiers(Modifier.PUBLIC, Modifier.FINAL).addMethod(mapMethod.build()).build();
    try {
        JavaFile.builder("com.github.mzule.activityrouter.router", routerMapping).build().writeTo(filer);
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return true;
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) Router(com.github.mzule.activityrouter.annotation.Router) ClassName(com.squareup.javapoet.ClassName) Name(javax.lang.model.element.Name) ClassName(com.squareup.javapoet.ClassName) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 98 with ClassName

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

the class InjectAdapterProcessor method generateStaticInjection.

/**
 * Write a companion class for {@code type} that extends {@link StaticInjection}.
 */
private void generateStaticInjection(TypeElement type, List<Element> fields) throws IOException {
    ClassName typeName = ClassName.get(type);
    ClassName adapterClassName = adapterName(ClassName.get(type), STATIC_INJECTION_SUFFIX);
    TypeSpec.Builder result = TypeSpec.classBuilder(adapterClassName.simpleName()).addOriginatingElement(type).addJavadoc(AdapterJavadocs.STATIC_INJECTION_TYPE, type).addModifiers(PUBLIC, FINAL).superclass(StaticInjection.class);
    for (Element field : fields) {
        result.addField(memberBindingField(false, field));
    }
    result.addMethod(attachMethod(null, fields, false, typeName, null, true));
    result.addMethod(staticInjectMethod(fields, typeName));
    String packageName = getPackage(type).getQualifiedName().toString();
    JavaFile javaFile = JavaFile.builder(packageName, result.build()).addFileComment(AdapterJavadocs.GENERATED_BY_DAGGER).build();
    javaFile.writeTo(processingEnv.getFiler());
}
Also used : 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) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 99 with ClassName

use of com.squareup.javapoet.ClassName in project CoreData by FangCloud-Android.

the class BindCursorMethod method bindCursorToField.

private void bindCursorToField(MethodSpec.Builder builder, Element element, String prefix) {
    // 基本类型
    // String
    // 内嵌类型
    // 关联类型
    // 转换类型
    ClassName stringClassName = ClassName.get(String.class);
    TypeName typeName = ClassName.get(element.asType());
    Element typeElement = processingEnv.getTypeUtils().asElement(element.asType());
    if (typeName.isPrimitive() || typeName.isBoxedPrimitive() || typeName.equals(stringClassName)) {
        // 基础类型 // 封装基础类型 // 字符串类型
        builder.addStatement(Utils.methodSetFormat(element, prefix), cursorGetMethod(element, Utils.getDbType(element)));
    } else {
        Embedded embedded = element.getAnnotation(Embedded.class);
        if (embedded != null) {
            // 内嵌类型循环添加
            // 创建临时变量
            String embeddedTempName = "__" + element.getSimpleName() + "Temp";
            builder.addStatement("$T $N = new $T()", typeName, embeddedTempName, typeName);
            // 赋值
            List<Element> elementsForDbEmbedded = new ArrayList<>();
            Utils.fillElementsForDbAndReturnPrimaryKey(processingEnv, elementsForDbEmbedded, (TypeElement) typeElement);
            ;
            for (Element eleEmbeddedChild : elementsForDbEmbedded) {
                bindCursorToField(builder, eleEmbeddedChild, embeddedTempName);
            }
            builder.addStatement(Utils.methodSetFormat(element, prefix), embeddedTempName);
            return;
        }
        Convert convert = element.getAnnotation(Convert.class);
        if (convert != null) {
            ClassName classConverter = ClassName.bestGuess(Utils.getConverterType(convert).toString());
            TypeName convertDbType = Utils.getConvertDbType(convert);
            if (!convertDbType.isPrimitive()) {
                builder.addCode("if(!cursor.isNull(cursorIndexOf$N)){\n  ", Utils.getColumnName(element));
            }
            builder.addStatement(Utils.methodSetFormat(element, prefix), Utils.converterName(element, classConverter) + ".convertToValue(" + cursorGetMethod(element, Utils.getDbType(element)) + ")");
            if (!convertDbType.isPrimitive()) {
                builder.addCode("}");
            }
            return;
        }
        Relation relation = element.getAnnotation(Relation.class);
        if (relation != null) {
            TypeElement typeRelation = (TypeElement) processingEnv.getTypeUtils().asElement(element.asType());
            EntityDetail relationEntityDetail = EntityDetail.parse(processingEnv, typeRelation);
            Element primaryKeyElement = relationEntityDetail.getPrimaryKey();
            if (primaryKeyElement != null) {
                TypeName typePrimary = ClassName.get(primaryKeyElement.asType());
                String columnName = Utils.getColumnName(element);
                if (!typePrimary.isPrimitive()) {
                    builder.addCode("if(!cursor.isNull(cursorIndexOf$N)){\n  ", columnName);
                }
                builder.addStatement("__$NMap.put($N, entity)", columnName, cursorGetMethod(element, Utils.getDbType(primaryKeyElement)));
                if (!typePrimary.isPrimitive()) {
                    builder.addCode("}");
                }
            }
            return;
        }
    }
}
Also used : ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) Relation(com.coredata.annotation.Relation) Convert(com.coredata.annotation.Convert) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) ClassName(com.squareup.javapoet.ClassName) ArrayList(java.util.ArrayList) Embedded(com.coredata.annotation.Embedded) EntityDetail(com.coredata.compiler.EntityDetail)

Aggregations

ClassName (com.squareup.javapoet.ClassName)99 TypeSpec (com.squareup.javapoet.TypeSpec)60 MethodSpec (com.squareup.javapoet.MethodSpec)41 TypeElement (javax.lang.model.element.TypeElement)37 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)35 TypeName (com.squareup.javapoet.TypeName)30 Element (javax.lang.model.element.Element)19 TypeMirror (javax.lang.model.type.TypeMirror)17 Builder (com.squareup.javapoet.TypeSpec.Builder)16 FieldSpec (com.squareup.javapoet.FieldSpec)15 ArrayList (java.util.ArrayList)15 CodeBlock (com.squareup.javapoet.CodeBlock)11 ExecutableElement (javax.lang.model.element.ExecutableElement)11 NotNull (org.jetbrains.annotations.NotNull)10 VariableElement (javax.lang.model.element.VariableElement)9 JavaFile (com.squareup.javapoet.JavaFile)8 Map (java.util.Map)8 WildcardTypeName (com.squareup.javapoet.WildcardTypeName)7 IOException (java.io.IOException)7 HashMap (java.util.HashMap)7