Issue
I was researching creating a generic sprint webflux based HTTP client and ran across code
public <T> ResponseWrapper<T> makeRequest(URI uri, Class<T> clazz) {
is that the same as <T,ResponseWrapper<T>>
I am not used to seeing two generic arguments on left hand side and not sure how to read/interpret it.
Is T
required before ResponseWrapper<T>
could you shorten it?
Solution
The first <T>
(directly after public
) declares a generic parameter for the method. ResponseWrapper<T>
then uses that parameter to declare the method's return type.
You can read it as "this method is public, has a generic parameter T
, and returns a ResponseWrapper<T>
." Without declaring that generic parameter, you wouldn't be able to declare a return value of ResponseWrapper<T>
: Java would tell you that it doesn't know what T
is in this context. (Remember that T
is also a perfectly valid class name — and Java doesn't want to guess at your intentions).
Note that if the class is also generic and has a T
parameter, this method's <T>
will declare a new parameter. That method-specific one is unrelated to the class's T
, and will shadow it — basically making the class's T
inaccessible.
Answered By - yshavit
Answer Checked By - Marilyn (JavaFixing Volunteer)