4

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?
Ankit Aggarwal
  • 5,317
  • 2
  • 30
  • 53

1 Answers1

4

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

Dean Xu
  • 4,438
  • 1
  • 17
  • 44
  • 5
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Nic3500 Nov 28 '18 at 18:51
  • 1
    @Nic3500 There isno why, just the API really there. – Dean Xu Nov 28 '18 at 21:20