Javapoet superclass generic

谁说胖子不能爱 提交于 2019-12-03 12:44:33
El Hoss

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!