JavaPoet Add Generic Parameter
Asked Answered
S

2

10

How would I generate a method with the following signature?

public <T extends MyClass> void doSomething(T t)

So far I have:

MethodSpec.methodBuilder("doSomething")
        .addModifiers(Modifier.PUBLIC)
        .addTypeVariable(TypeVariableName.get("T", MyClass.class))
        .build()

EDIT This is what the above code is generating (I don't know how to add the parameter):

public <T extends Myclass> void doSomething()
Steelyard answered 21/6, 2015 at 22:32 Comment(0)
K
16

Extract the TypeVariableName you generate into a variable so you can reuse its value

TypeVariableName typeVariableName = TypeVariableName.get("T", MyClass.class);

Then add a parameter of that type

MethodSpec spec = MethodSpec.methodBuilder("doSomething")
                            .addModifiers(Modifier.PUBLIC)
                            .addTypeVariable(typeVariableName)
                            .addParameter(typeVariableName, "t") // you can also add modifiers
                            .build();
Kaliski answered 21/6, 2015 at 22:38 Comment(0)
S
4

If you want to pass a Generic typed structure, use the follow way.

MethodSpec loadListInteger = MethodSpec.methodBuilder("loadListInteger")
                    .addModifiers(Modifier.PUBLIC)
                    .returns(void.class)
                    .addParameter(ParameterizedTypeName.get(List.class, Integer.class), "list")
                    .build();
Shoifet answered 19/9, 2016 at 7:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.