Javapoet superclass generic
Asked Answered
I

1

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();
}
Inefficient answered 4/5, 2016 at 13:2 Comment(0)
E
23

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.

Ethelind answered 4/5, 2016 at 17:44 Comment(1)
You can also do ParameterizedTypeName.get(MyMapper.class, OtherClass.class), it seems.Renata

© 2022 - 2024 — McMap. All rights reserved.