Search code examples
javaannotationsjava-6annotation-processing

How to get the type of a field in an annotation processor?


I'm trying to write an annotation to check if an object is immutable at runtime. In order to do so, I check if the class of the object is final and then if all its attributes are also final. And then, I want to check the same thing recursively for the type of each field if it's not a primitive type.

Here a piece of code:

for (Element subElement : element.getEnclosedElements()) {
    if (subElement.getKind().isField()) {
        isFinal=false;

        for(Modifier modifier : subElement.getModifiers()) {
            if (modifier.equals(Modifier.FINAL)) {
                isFinal=true;
                break;
            }
        }
        if (!isFinal) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Field "+element+" is not immutable because it is not final");
        } else {
            // Here I want to restart my method recursively
        }
    }
}

How can I get my method to start all over again with the type of my field? How can I retrieve the type of the field, which is here a javax.lang.model.element.Element?

Edit: I need the type as declared in the containing class, which needs to be a final class to avoid any kind of mutability.


Solution

  • I've been able to do it with Square's javapoet ClassName class:

    Element element = ...
    ClassName className = ClassName.get(element.asType());
    String name = className.toString();
    

    If, for example, the annotated field is a String, it will return Java.lang.String. I'm open to a better solution than this one.