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
)?
The
<T>
part is declaring a generic type argumentT
. If you were to omit this part, the compiler would likely complain that the typeT
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.This declares the
readObjectData
method generic, with one type parameter,T
.Then the return type is
T
.Without the initial
<T>
, which is the generic type declaration, the symbolT
will be undefined.In the parameter list,
Class<T> type
is one of the parameters. Because the return type and this parameter both referenceT
, this ensures that if you pass in aClass<String>
, then it will return aString
. If you pass in aClass<Double>
, then it will return aDouble
.To pass in the parameter, pass in any
Class
object, e.g.String.class
.<T>
is a parameter class. There is no class namedT
. You can use this method with any class specified via second method argument namedtype
.since method is defined as following:
public <T> T readObjectData(ByteBuffer buffer, Class<T> type)
You can call it as written below:
MyClass obj = o.readObjectData(buffer, MyClass.class);
Please pay attention that you do not have to cast return value of
readOjectData()
toMyClass
. Once upon a time, before java 5 this method would be defined as:public Object readObjectData(ByteBuffer)
and its usage looked like:
MyClass obj = (MyClass)o.readObjectData(buffer);
Since casting may cause
ClassCastException
this is a bad practice. This was a reason for invention of generics.You are probably confused by a similar and more common declaration:
In above case, there is no need for
"<T>"
after private (private <T> T myMethod(T a)
)because the
T
it's using is the same than the one defined in the classMyClass<T>
Even more, if you write
then the meaning is that the myMethod return type is (potentially) different than the MyClass type. As if you wrote this instead:
Credits: Took the example from "Kanagavelu Sugumar"'s longer answer to How to use Class<T> in Java?