Search code examples
javaandroidgenericsjavapoet

Javapoet superclass generic


Anyone know how I can do the following using javapoet

public class MyClassGenerated extends MyMapper<OtherClass>{

}

My code of generation:

TypeSpec generateClass() {
    return classBuilder("MyClassGenerated")
         .addModifiers(PUBLIC)
         .superclass(???????????????)
         .build();
}

Solution

  • The ParameterizedTypeName class allows you to specify generic type arguments when declaring the super class. For instance, if your MyClassGenerated class is a subclass of the MyMapper class, you can set a generic type parameter of MyMapper like so:

    TypeSpec classSpec = classBuilder("MyClassGenerated")
         .addModifiers(PUBLIC)
         .superclass(ParameterizedTypeName.get(ClassName.get(MyMapper.class),  
                                               ClassName.get(OtherClass.class)))
         .build();
    

    This will generate a TypeSpec object that is equivalent to the following class:

    public class MyClassGenerated extends MyMapper<OtherClass> { }
    

    While not specified in the question, note that you can set any number of generic type arguments by simply adding them in the correct order to the ParameterizedTypeName.get call:

    ParameterizedTypeName.get( 
        ClassName.get(SuperClass.class),
        ClassName.get(TypeArgumentA.class),
        ClassName.get(TypeArgumentB.class),
        ClassName.get(TypeArgumentC.class)
    ); // equivalent to SuperClass<TypeArgumentA, TypeArgumentB, TypeArgumentC>
    

    For more information about the ParameterizedTypeName.get() method, see the documentation here or the "$T for Types" section of the JavaPoet GitHub page.