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.

1 Answer 1

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]

Sign up to request clarification or add additional context in comments.

2 Comments

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().
@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 .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.