Search code examples
javaandroidannotationsjavapoet

JavaPoet - get generic type


I'm playing around with annotation processor and JavaPoet. I have a method which I annotated with @MyAnno:

@MyAnno
Observable<MyClass> get(int id);

I want to generate a class which will have a method:

AsyncSubject<MyClass> get(int id);

What I've done so far is:

ClassName classAsyncSubject = ClassName.get("rx.subjects", "AsyncSubject");
TypeName newReturnType = ParameterizedTypeName.get(classAsyncSubject, get(executableElement.getReturnType()));

which gives me:

AsyncSubject<Observable<MyClass>>

How to get only MyClass?


Solution

  • If your returned type always is an Observable<X>, you might cast the result from get(executableElement.getReturnType()) to ParameterizedTypeName and access the first type argument:

    ((ParameterizedTypeName) get(executableElement.getReturnType()).typeArguments.get(0)
    

    Type, capacity and sanity checks apply.