JavaPoet Add General Parameter

How do I generate a method with the following signature?

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

So far, I:

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

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

 public <T extends Myclass> void doSomething() 
+6
source share
2 answers

Extract the TypeVariableName you create into the variable so you can reuse its value

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

Then add a parameter of this type

 MethodSpec spec = MethodSpec.methodBuilder("doSomething") .addModifiers(Modifier.PUBLIC) .addTypeVariable(typeVariableName) .addParameter(typeVariableName, "t") // you can also add modifiers .build(); 
+10
source

If you want to pass a typed typed structure, use the following path.

 MethodSpec loadListInteger = MethodSpec.methodBuilder("loadListInteger") .addModifiers(Modifier.PUBLIC) .returns(void.class) .addParameter(ParameterizedTypeName.get(List.class, Integer.class), "list") .build(); 
+1
source

Source: https://habr.com/ru/post/989489/


All Articles