vendredi 16 décembre 2016

Identify fields that are annotated in the source files

I am writing an annotation processor that generates from a POJO the equivalent that extends RealmObject. I need help to found out if a field of the annotated class is an object that's also annotated in its source file, so i use the its generated file in the file that i am generating. Here is the code:

@AutoMap // my custom annotation
public class UserModel {
    @PrimaryKey
    private int id;
    private String coverUrl;
    private String fullName;
    private String description;
    private int followers;
    private String email;
    private List<RepoModel> repos; // field that is annotated in its source code

    public UserModel() {
    }
}


@AutoMap // the annotation in the source code
public class RepoModel {

    private String name;
    @PrimaryKey
    private String url;

    public RepoModel() {
    }
}
// In my annotation Processor
private String generateDataClassFile(TypeElement type, String className) {
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className)
            .superclass(ClassName.get("io.realm", "RealmObject"))
            .addModifiers(Modifier.PUBLIC)
            .addMethod(constructor);
    List<? extends Element> allElements = type.getEnclosedElements();
    for (int i = 0, allElementsSize = allElements.size(); i < allElementsSize; i++) {
        Element element = allElements.get(i);
        if (element.getKind().isField()) {
                TypeName typeName = TypeName.get(element.asType());
                String variableName = element.getSimpleName().toString();
                FieldSpec.Builder builder;
               if (/* what should i check*/)
                   builder = FieldSpec.builder(/* How can i get the generated file */, variableName);
               else
                   builder = FieldSpec.builder(typeName, variableName);
       }
    classBuilder.addField(builder.build());
    return JavaFile.builder(pkg, classBuilder.build()).build().toString();
}

The aim is to replace all fields with their generated counter parts, to have a coherent RealmObject. Thanks in advance.

Desired result:

public class AutoMap_UserModel extends RealmObject{
    @PrimaryKey
    private int id;
    private String coverUrl;
    private String fullName;
    private String description;
    private int followers;
    private String email;
    private List<AutoMap_RepoModel> repos; // The current version generates List<RepoModel>

    public AutoMap_UserModel() {
    }
}





Aucun commentaire:

Enregistrer un commentaire