6

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?

Michael
  • 32,527
  • 49
  • 210
  • 370

1 Answers1

9

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.

John Ericksen
  • 10,995
  • 4
  • 45
  • 75