10

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();
}
endian
  • 4,761
  • 7
  • 32
  • 54
Marco Giovanni
  • 297
  • 7
  • 18

1 Answers1

22

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.

otoomey
  • 939
  • 1
  • 14
  • 31
El Hoss
  • 3,767
  • 2
  • 18
  • 24