0

I am trying to use an annotation processor to validate annotations, and as part of that effort, I am trying to figure out how to use the API to determine if a Parameter of an ExecutableElement is a parameterized type (such as List<Foo>), and if so, what the parameterized type(s) are (Foo).

Is there any way to do this besides just parsing the string given by ve.asType().toString() where VariableElement ve is an element of ExecutableElement e.getParameters()? It would be nice to have a better handle on those types than just simply a string.

Zach
  • 11
  • 2

1 Answers1

1

The idea is to know when to cast to what, in your case you need to obtain the generic type argument, so you need to cast to DeclaredType .

for example for a method like the following

@SampleAnno
public void something(List<String> paramx){

}

a code in a processor like this

ExecutableElement method = (ExecutableElement) this.sampleElement;

method.getParameters()
        .forEach(parameter -> ((DeclaredType)parameter.asType()).getTypeArguments()
                .forEach(typeMirror -> {
                 messager.printMessage(Diagnostic.Kind.NOTE, "::::::: > [" + typeMirror.toString() + "]");
                }));

should print Information:java: ::::::: > [java.lang.String]

Ahmad Bawaneh
  • 1,014
  • 8
  • 23
  • 1
    Only caveat: here, as in the question, be very careful with `toString()`, sometimes this doesn't behave right (Eclipse's JDT for example). Instead, consider something like JavaPoet's `TypeName.get(...)` or `ClassName.get(...)`, which _does_ have a good, consistent toString(). – Colin Alworth Apr 24 '19 at 23:44
  • @ColinAlworth yes you are right ..i only did this to just demo that i can get the typeMirror from the generic type of the parameter..but normally i would get it to do something useful with it.. i always use JavaPoet . – Ahmad Bawaneh Apr 25 '19 at 06:05