Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get TypeElement from Generic TypeParameterElement for Java Annotation Processor?

Using Java Annotation Processors I have the following type:

@NameToken(value={"startPage"})
public interface MyProxy extends Proxy<StartPagePresenter> {
}

and:

public interface Proxy<T> { }

I have the TypeElement of Proxyas:

TypeElement pProxyTypeElement = // ...

Now I want to get the TypeElement of the Type Parameter <StartPagePresenter>.

I tried:

List<? extends TypeParameterElement> proxyTypeParamElems = 
                                         proxyTypeElement.getTypeParameters();
TypeParameterElement firstParameter = proxyTypeParamElems.get(0);

When I print firstParameter.getSimpleName() I get T instead of StartPagePresenter.

How do I get the real TypeElement StartPagePresenter from the TypeParameter?

like image 342
confile Avatar asked Apr 28 '15 14:04

confile


1 Answers

To access the generic paramters, you'll need the TypeMirror cast to a DeclaredType. DeclaredType has a method getTypeArguments() which returns a list of TypeMirror which represent the concrete declared generic parameters:

Following your example:

    Set<? extends Element> proxyElements = roundEnvironment.getElementsAnnotatedWith(NameToken.class);

    for(Element element : proxyElements){
        TypeElement typeElement = (TypeElement)element;
        DeclaredType declaredType = (DeclaredType)typeElement.getInterfaces().get(0); //assuming there is an interface

        for(TypeMirror genericParameter : declaredType.getTypeArguments()){
            messager.printMessage(Diagnostic.Kind.NOTE, genericParameter.toString());
        }
    }

Should print StartPagePresenter

I prefer using the various visitors supplied with the API to smooth out this casting.

like image 91
John Ericksen Avatar answered Nov 15 '22 06:11

John Ericksen