Generic Definitions on Static Methods
MorningSage opened this issue · comments
Thank you for creating this library. I have found it immensely helpful!
One thing I haven't wrapped my head around is how to declare a generic type in a static method. For instance, I would like to generate this code:
// Goal is to define <X> as follows
public static <X> Builder<X> builder() {
return new Builder<>();
}
I can successfully create the method, but <X>
is undefined because this is a static function.
// Actual code generated where <X> is not defined
public static Builder<X> builder() {
return new Builder<>();
}
Is there a way to define <X>
as is the first example? Can I pass a GenericSourceGenerator
somewhere or set a flag I'm missing? The code I'm using is fairly dynamic, but a simplified version is:
FunctionSourceGenerator.create("builder")
.addModifier(Modifier.PUBLIC | Modifier.STATIC)
.setReturnType(
TypeDeclarationSourceGenerator.create("Builder").addGeneric(GenericSourceGenerator.create("X"))
)
.addBodyCodeLine("return new Builder<>();")
Thanks!
Hello, Thank you for your feedback! :-)
To solve your problem you need to call FunctionSourceGenerator
's setTypeDeclaration
method as follow:
FunctionSourceGenerator.create("builder")
.addModifier(Modifier.PUBLIC | Modifier.STATIC)
.setTypeDeclaration(
TypeDeclarationSourceGenerator.create(
GenericSourceGenerator.create("X")
)
)
.setReturnType(
TypeDeclarationSourceGenerator.create("Builder").addGeneric(GenericSourceGenerator.create("X"))
)
For further examples you can also visit the UnitSourceGeneratorTest
class that contains a series of tests that together represent a complete example of what you can do with source generators.