I have this Java code.
public <T> T readObjectData(ByteBuffer buffer, Class<T> type) { ... T retVal = (T) summaries; return retVal;
How to interpret this code? Why do we need public <T> T
instead of public T
?
How to give the parameter to the 2nd argument (Class<T> type
)?
T is type parameters (also called type variables); delimited by angle brackets (<>), follows the class name. T is just a symbol, like a variable name (can be any name) declared during writing of the class file.
super T denotes an unknown type that is a supertype of T (or T itself; remember that the supertype relation is reflexive). It is the dual of the bounded wildcards we've been using, where we use ? extends T to denote an unknown type that is a subtype of T .
In Java there's a single metaclass: Class . Its instances (only one per type exists) are used to represent classes and interfaces, therefore the T in Class<T> refers to the type of the class or interface that the current instance of Class represents.
Q - Economy/Coach Discounted. R - First Class Suite or Supersonic (discontinued) S - Economy/Coach. T - Economy/Coach Discounted.
This declares the readObjectData
method generic, with one type parameter, T
.
public <T> ...
Then the return type is T
.
... T readObjectData(...
Without the initial <T>
, which is the generic type declaration, the symbol T
will be undefined.
In the parameter list, Class<T> type
is one of the parameters. Because the return type and this parameter both reference T
, this ensures that if you pass in a Class<String>
, then it will return a String
. If you pass in a Class<Double>
, then it will return a Double
.
To pass in the parameter, pass in any Class
object, e.g. String.class
.
The <T>
part is declaring a generic type argument T
. If you were to omit this part, the compiler would likely complain that the type T
doesn't exist.
In this case, T
serves as a placeholder for an actual type, which will only be determined when the method is actually called with non-generic type arguments.
public <T> T readObjectData(... ^ ^ | + Return type + Generic type argument
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With