Search in sources :

Example 91 with TypeMirror

use of javax.lang.model.type.TypeMirror in project butterknife by JakeWharton.

the class ButterKnifeProcessor method parseResourceDimen.

private void parseResourceDimen(Element element, Map<TypeElement, BindingSet.Builder> builderMap, Set<TypeElement> erasedTargetNames) {
    boolean hasError = false;
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
    // Verify that the target type is int or ColorStateList.
    boolean isInt = false;
    TypeMirror elementType = element.asType();
    if (elementType.getKind() == TypeKind.INT) {
        isInt = true;
    } else if (elementType.getKind() != TypeKind.FLOAT) {
        error(element, "@%s field type must be 'int' or 'float'. (%s.%s)", BindDimen.class.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName());
        hasError = true;
    }
    // Verify common generated code restrictions.
    hasError |= isInaccessibleViaGeneratedCode(BindDimen.class, "fields", element);
    hasError |= isBindingInWrongPackage(BindDimen.class, element);
    if (hasError) {
        return;
    }
    // Assemble information on the field.
    String name = element.getSimpleName().toString();
    int id = element.getAnnotation(BindDimen.class).value();
    QualifiedId qualifiedId = elementToQualifiedId(element, id);
    BindingSet.Builder builder = getOrCreateBindingBuilder(builderMap, enclosingElement);
    builder.addResource(new FieldResourceBinding(getId(qualifiedId), name, isInt ? FieldResourceBinding.Type.DIMEN_AS_INT : FieldResourceBinding.Type.DIMEN_AS_FLOAT));
    erasedTargetNames.add(enclosingElement);
}
Also used : TypeMirror(javax.lang.model.type.TypeMirror) BindDimen(butterknife.BindDimen) TypeElement(javax.lang.model.element.TypeElement) BindString(butterknife.BindString)

Example 92 with TypeMirror

use of javax.lang.model.type.TypeMirror in project vertx-docgen by vert-x3.

the class JavaDocGenerator method toExecutableLink.

private String toExecutableLink(ExecutableElement elt, String name) {
    TypeElement typeElt = (TypeElement) elt.getEnclosingElement();
    String link = resolveTypeLink(typeElt, null);
    StringBuilder anchor = new StringBuilder("#");
    anchor.append(name).append('-');
    TypeMirror type = elt.asType();
    ExecutableType methodType = (ExecutableType) processingEnv.getTypeUtils().erasure(type);
    List<? extends TypeMirror> parameterTypes = methodType.getParameterTypes();
    for (int i = 0; i < parameterTypes.size(); i++) {
        if (i > 0) {
            anchor.append('-');
        }
        // We need to check whether or not the parameter is annotated. In this case, we must use the unannotated type.
        TypeMirror typeOfParameter = parameterTypes.get(i);
        if (typeOfParameter instanceof Type && ((Type) typeOfParameter).isAnnotated()) {
            anchor.append(((Type) typeOfParameter).unannotatedType().toString());
        } else {
            anchor.append(typeOfParameter.toString());
        }
    }
    anchor.append('-');
    return link + anchor;
}
Also used : ExecutableType(javax.lang.model.type.ExecutableType) ExecutableType(javax.lang.model.type.ExecutableType) Type(com.sun.tools.javac.code.Type) TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement)

Example 93 with TypeMirror

use of javax.lang.model.type.TypeMirror in project CoreData by FangCloud-Android.

the class EntityProcessor method createEntityDao.

public void createEntityDao(TypeElement element) throws IOException {
    EntityDetail entityDetail = EntityDetail.parse(processingEnv, element);
    // 实体类的class
    ClassName classEntity = ClassName.bestGuess(element.asType().toString());
    if (entityDetail.getPrimaryKey() == null) {
        throw new RuntimeException(classEntity.reflectionName() + " 没有主键");
    }
    List<Property> propertyList = entityDetail.getProperties(processingEnv);
    // 1、找出tableName,PrimaryKeyName ok
    // 2、找出所有的PropertyConverter,并生成局部变量,类似 __TagListConverter ok
    // 3、找出所有关联对象 @Relation,并生成对应的dao 类似 __AuthorCoreDao ok
    // 4、onCreate方法,初始化 关联对象对应的 dao ok
    // 5、getInsertSql, 返回插入的sql语句 ok
    // 6、getCreateTableSql,返回建表语句
    // 7、getTableProperties,返回所有的表结构
    // 8、绑定数据
    // dao的java名字
    String daoName = String.format("%sCoreDaoImpl", entityDetail.getEntityName());
    TypeSpec.Builder daoTypeBuilder = TypeSpec.classBuilder(daoName).addModifiers(Modifier.PUBLIC, Modifier.FINAL).superclass(ParameterizedTypeName.get(classCoreDao, classEntity));
    List<Element> convertElements = entityDetail.getConvertElements(processingEnv);
    // static 代码块
    CodeBlock convertStaticBlock = CreateConvertStatement.buildConvertStatic(convertElements);
    if (convertStaticBlock != null) {
        daoTypeBuilder.addStaticBlock(convertStaticBlock);
    }
    // 创建convert
    List<FieldSpec> convertFieldSpecs = CreateConvertStatement.bindComvertFields(convertElements);
    if (convertFieldSpecs != null) {
        for (FieldSpec fieldSpec : convertFieldSpecs) {
            daoTypeBuilder.addField(fieldSpec);
        }
    }
    // onCreate方法
    // 创建关联的dao
    List<Element> relationElements = entityDetail.getRelationElements();
    MethodSpec.Builder onCreateMethodBuilder = MethodSpec.methodBuilder("onCreate").addModifiers(Modifier.PROTECTED).returns(void.class).addParameter(classCoreData, "coreData").addStatement("super.onCreate($N)", "coreData");
    for (Element relationElement : relationElements) {
        TypeMirror typeMirror = relationElement.asType();
        ClassName classRelation = ClassName.bestGuess(typeMirror.toString());
        String daoFieldName = Utils.relationDaoName(classRelation);
        FieldSpec fieldSpec = FieldSpec.builder(ParameterizedTypeName.get(classCoreDao, classRelation), daoFieldName, Modifier.PRIVATE).build();
        daoTypeBuilder.addField(fieldSpec);
        onCreateMethodBuilder.addStatement("$N = coreData.dao($T.class)", daoFieldName, classRelation);
    }
    MethodSpec onCreateMethod = onCreateMethodBuilder.build();
    // getCreateTableSql 方法,用来获取建表语句
    MethodSpec getCreateTableSqlMethod = MethodSpec.methodBuilder("getCreateTableSql").addModifiers(Modifier.PROTECTED).returns(String.class).addStatement("return $S", SqlBuilder.buildCreateSql(entityDetail.getTableName(), propertyList, true)).build();
    // getInsertSql 方法,用来获取插入语句
    MethodSpec getInsertSqlMethod = MethodSpec.methodBuilder("getInsertSql").addModifiers(Modifier.PROTECTED).returns(String.class).addStatement("return $S", Utils.getInsertSql(entityDetail.getTableName(), propertyList)).build();
    // bindStatement 用来绑定数据
    MethodSpec bindStatementMethod = new BindStatementMethod(processingEnv, entityDetail).build();
    // replaceInternal 方法,用来处理关系型数据
    MethodSpec replaceInternalMethod = new ReplaceInternalMethod(processingEnv, entityDetail).build();
    // 创建 getTableName 方法,返回tableName
    MethodSpec getTableNameMethod = MethodSpec.methodBuilder("getTableName").addModifiers(Modifier.PUBLIC).returns(String.class).addStatement("return $S", entityDetail.getTableName()).build();
    // 创建 getPrimaryKeyName 方法,返回 主键的名字
    MethodSpec getPrimaryKeyNameMethod = MethodSpec.methodBuilder("getPrimaryKeyName").addModifiers(Modifier.PUBLIC).returns(String.class).addStatement("return $S", Utils.getColumnName(entityDetail.getPrimaryKey())).build();
    // 创建 bindCursor 方法,绑定游标数据到模型
    MethodSpec bindCursorMethod = new BindCursorMethod(processingEnv, entityDetail).build();
    // 创建 getTableProperties 方法,返回所有字段相关的 Property
    ParameterizedTypeName listPropertyType = ParameterizedTypeName.get(ClassName.get(ArrayList.class), classCoreProperty);
    MethodSpec.Builder getTablePropertiesBuilder = MethodSpec.methodBuilder("getTableProperties").addModifiers(Modifier.PUBLIC).returns(ParameterizedTypeName.get(ClassName.get(List.class), classCoreProperty));
    getTablePropertiesBuilder.addStatement("$T list = new $T()", listPropertyType, listPropertyType);
    for (Property property : propertyList) {
        getTablePropertiesBuilder.addStatement("list.add(new $T($S, $T.class, $N))", classCoreProperty, property.name, Utils.getTypeNameByType(property.type), String.valueOf(property.primaryKey));
    }
    getTablePropertiesBuilder.addStatement("return list");
    daoTypeBuilder.addMethod(onCreateMethod).addMethod(getTableNameMethod).addMethod(getPrimaryKeyNameMethod).addMethod(getTablePropertiesBuilder.build()).addMethod(getCreateTableSqlMethod).addMethod(getInsertSqlMethod).addMethod(bindStatementMethod).addMethod(replaceInternalMethod).addMethod(bindCursorMethod);
    JavaFile javaFile = JavaFile.builder(entityDetail.getEntityPackageName(processingEnv), daoTypeBuilder.build()).build();
    javaFile.writeTo(processingEnv.getFiler());
    System.out.println(element.getSimpleName());
    System.out.println(processingEnv.getElementUtils().getPackageOf(element).getQualifiedName());
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) CodeBlock(com.squareup.javapoet.CodeBlock) ArrayList(java.util.ArrayList) BindCursorMethod(com.coredata.compiler.method.BindCursorMethod) FieldSpec(com.squareup.javapoet.FieldSpec) ReplaceInternalMethod(com.coredata.compiler.method.ReplaceInternalMethod) BindStatementMethod(com.coredata.compiler.method.BindStatementMethod) TypeMirror(javax.lang.model.type.TypeMirror) ClassName(com.squareup.javapoet.ClassName) JavaFile(com.squareup.javapoet.JavaFile) Property(com.coredata.db.Property) TypeSpec(com.squareup.javapoet.TypeSpec) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Example 94 with TypeMirror

use of javax.lang.model.type.TypeMirror in project CoreData by FangCloud-Android.

the class BindCursorMethod method bind.

private void bind(MethodSpec.Builder builder) {
    // final int cursorIndexOfId = cursor.getColumnIndexOrThrow("id");
    // final int cursorIndexOfName = cursor.getColumnIndexOrThrow("name");
    // final int cursorIndexOfTags = cursor.getColumnIndexOrThrow("tags");
    // final int cursorIndexOfAuthor = cursor.getColumnIndexOrThrow("author_id");
    // final int cursorIndexOfContent = cursor.getColumnIndexOrThrow("desc_content");
    // final int cursorIndexOfEmail = cursor.getColumnIndexOrThrow("desc_email");
    // List<Book> bookList = new ArrayList<>();
    // Map<Integer, Book> authorIdWithBookMap = new HashMap<>();
    // while (cursor.moveToNext()) {
    // Book book = new Book();
    // book.id = cursor.getLong(cursorIndexOfId);
    // book.name = cursor.getString(cursorIndexOfName);
    // book.tags = __TagListConverter.convertToValue(cursor.getString(cursorIndexOfTags));
    // int authorId = cursor.getInt(cursorIndexOfAuthor);
    // book.desc = new Desc();
    // book.desc.content = cursor.getString(cursorIndexOfContent);
    // book.desc.email = cursor.getString(cursorIndexOfEmail);
    // bookList.add(book);
    // authorIdWithBookMap.put(authorId, book);
    // }
    // List<Author> authorList = __authorCoreDao.queryByKeys(authorIdWithBookMap.keySet().toArray(new Integer[]{}));
    // for (Author author : authorList) {
    // Book book = authorIdWithBookMap.get(author.getId());
    // if (book != null) {
    // book.author = author;
    // }
    // }
    // return bookList;
    TypeName typeNameEntity = ClassName.get(entityDetail.getEntityElement().asType());
    ParameterizedTypeName typeListEntity = ParameterizedTypeName.get(ClassName.get(ArrayList.class), typeNameEntity);
    List<Element> elementsForDb = entityDetail.getDbElements();
    List<Property> properties = entityDetail.getProperties(processingEnv);
    List<Element> relationElements = entityDetail.getRelationElements();
    for (Property property : properties) {
        builder.addStatement("int $N = cursor.getColumnIndexOrThrow($S)", "cursorIndexOf" + property.name, property.name);
    }
    // 创建自己的列表
    builder.addStatement("$T list = new $T()", typeListEntity, typeListEntity);
    // 创建多个关联数据的hashMap,主键类型为key
    for (Element relationElement : relationElements) {
        TypeElement typeRelation = (TypeElement) processingEnv.getTypeUtils().asElement(relationElement.asType());
        EntityDetail relationEntityDetail = EntityDetail.parse(processingEnv, typeRelation);
        Element primaryKeyElement = relationEntityDetail.getPrimaryKey();
        if (primaryKeyElement != null) {
            TypeMirror typeMirror = primaryKeyElement.asType();
            ParameterizedTypeName hashMapType = ParameterizedTypeName.get(ClassName.get(HashMap.class), ClassName.get(typeMirror).box(), typeNameEntity);
            builder.addStatement("$T __$NMap = new $T()", hashMapType, Utils.getColumnName(relationElement), hashMapType);
        }
    }
    builder.addCode("while (cursor.moveToNext()) {\n  ");
    // 创建一个对象
    String itemName = "entity";
    builder.addStatement("$T $N = new $T()", typeNameEntity, itemName, typeNameEntity);
    for (Element element : elementsForDb) {
        bindCursorToField(builder, element, itemName);
    }
    builder.addStatement("list.add(entity)");
    // 将对象放入相应关联对象对应的map
    builder.addCode("}\n");
    // 循环关联对象,赋值给主对象
    for (Element relationElement : relationElements) {
        ClassName classNameRelation = ClassName.bestGuess(relationElement.asType().toString());
        TypeElement typeRelationElement = (TypeElement) processingEnv.getTypeUtils().asElement(relationElement.asType());
        EntityDetail relationEntityDetail = EntityDetail.parse(processingEnv, typeRelationElement);
        Element primaryKeyElement = relationEntityDetail.getPrimaryKey();
        if (primaryKeyElement != null) {
            // List<Author> authorList = __authorCoreDao.queryByKeys(authorIdWithBookMap.keySet().toArray(new Integer[]{}));
            TypeName primaryTypeName = ClassName.get(primaryKeyElement.asType());
            ParameterizedTypeName listRelationType = ParameterizedTypeName.get(ClassName.get(List.class), classNameRelation);
            String listName = String.format("__%sList", typeRelationElement.getSimpleName());
            String mapName = String.format("__%sMap", Utils.getColumnName(relationElement));
            builder.addStatement("$T $N = $N.queryByKeys($N.keySet().toArray(new $T[]{}))", listRelationType, listName, Utils.relationDaoName(classNameRelation), mapName, primaryTypeName.box());
            builder.addCode("for($T item : $N){\n", classNameRelation, listName);
            builder.addStatement("  $T entity = $N.get($N)", typeNameEntity, mapName, Utils.methodGet(primaryKeyElement, "item"));
            builder.addCode("  if(entity != null){\n");
            builder.addStatement(Utils.methodSetFormat(relationElement, "entity"), "item");
            builder.addCode("  }\n");
            builder.addCode("}\n");
        }
    }
    builder.addStatement("return list");
}
Also used : ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) HashMap(java.util.HashMap) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) ArrayList(java.util.ArrayList) TypeMirror(javax.lang.model.type.TypeMirror) ClassName(com.squareup.javapoet.ClassName) ArrayList(java.util.ArrayList) List(java.util.List) EntityDetail(com.coredata.compiler.EntityDetail) Property(com.coredata.db.Property) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName)

Example 95 with TypeMirror

use of javax.lang.model.type.TypeMirror in project checker-framework by typetools.

the class AnnotationBuilder method checkSubtype.

// TODO: this method always returns true and no-one ever looks at the return
// value.
private boolean checkSubtype(TypeMirror expected, Object givenValue) {
    if (expected.getKind().isPrimitive()) {
        expected = types.boxedClass((PrimitiveType) expected).asType();
    }
    if (expected.getKind() == TypeKind.DECLARED && TypesUtils.isClass(expected) && givenValue instanceof TypeMirror) {
        return true;
    }
    TypeMirror found;
    boolean isSubtype;
    if (expected.getKind() == TypeKind.DECLARED && ((DeclaredType) expected).asElement().getKind() == ElementKind.ANNOTATION_TYPE && givenValue instanceof AnnotationMirror) {
        found = ((AnnotationMirror) givenValue).getAnnotationType();
        isSubtype = ((DeclaredType) expected).asElement().equals(((DeclaredType) found).asElement());
    } else if (givenValue instanceof AnnotationMirror) {
        found = ((AnnotationMirror) givenValue).getAnnotationType();
        // TODO: why is this always failing???
        isSubtype = false;
    } else if (givenValue instanceof VariableElement) {
        found = ((VariableElement) givenValue).asType();
        if (expected.getKind() == TypeKind.DECLARED) {
            isSubtype = types.isSubtype(types.erasure(found), types.erasure(expected));
        } else {
            isSubtype = false;
        }
    } else {
        found = elements.getTypeElement(givenValue.getClass().getCanonicalName()).asType();
        isSubtype = types.isSubtype(types.erasure(found), types.erasure(expected));
    }
    if (!isSubtype) {
        if (types.isSameType(found, expected)) {
            ErrorReporter.errorAbort("given value differs from expected, but same string representation; " + "this is likely a bootclasspath/classpath issue; " + "found: " + found);
        } else {
            ErrorReporter.errorAbort("given value differs from expected; " + "found: " + found + "; expected: " + expected);
        }
        // dead code
        return false;
    }
    return true;
}
Also used : AnnotationMirror(javax.lang.model.element.AnnotationMirror) TypeMirror(javax.lang.model.type.TypeMirror) VariableElement(javax.lang.model.element.VariableElement) DeclaredType(javax.lang.model.type.DeclaredType)

Aggregations

TypeMirror (javax.lang.model.type.TypeMirror)1086 TypeElement (javax.lang.model.element.TypeElement)419 ExecutableElement (javax.lang.model.element.ExecutableElement)259 VariableElement (javax.lang.model.element.VariableElement)237 Element (javax.lang.model.element.Element)196 DeclaredType (javax.lang.model.type.DeclaredType)177 ArrayList (java.util.ArrayList)154 Test (org.junit.Test)152 AnnotationMirror (javax.lang.model.element.AnnotationMirror)75 Types (javax.lang.model.util.Types)70 List (java.util.List)66 Elements (javax.lang.model.util.Elements)60 HashSet (java.util.HashSet)53 ArrayCodeTypeMirror (com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror.ArrayCodeTypeMirror)50 Map (java.util.Map)49 ExecutableType (javax.lang.model.type.ExecutableType)45 MethodSpec (com.squareup.javapoet.MethodSpec)44 PackageElement (javax.lang.model.element.PackageElement)41 ArrayType (javax.lang.model.type.ArrayType)41 Expression (com.google.devtools.j2objc.ast.Expression)39