Java Annotation Processing how to check if VariableElement is a primitive type(int, float) or an object some class

805 views Asked by At

I have a class

public class SomeClass {

    @CustomAnnotation1
    String stringProperty = "LALALA";

    @CustomAnnotation1
    int integerProperty;

    @CustomAnnotation1
    ClassObject classObject;
}

CustomAnnotation1 is a custom annotation defined by me which can be put over any Field. Suppose class ClassObject is something like

public class ClassObject {

    @CustomAnnotation1
    public String someOtherString;

    public String log;
}

What I want to achieve - If my annotation is put on any field which is not a primitive type, I want to access all the fields of that class.

My Approach - Get all the fields annotated with CustomAnnotation1, iterate over all of them and if it is non-primitive, get all the fields inside that class and process.

What I've tried - I am able to get all the elements annotated with my annotation using the below code in my AbstractProcessor class.

Collection<? extends Element> annotatedElements = roundEnvironment.getElementsAnnotatedWith(CustomAnnotation1.class);
List<VariableElement> variableElements = ElementFilter.fieldsIn(annotatedElements);

Questions -

  • I've researched a lot about the VariableElement class but unable to find a way to check if the field is primitive or not. Can this be done?
  • Is there any better approach to achieve this?
1

There are 1 answers

2
Dean Xu On BEST ANSWER

VariableElement.asType().getKind().isPrimitive()