prosseek prosseek - 1 month ago 12
Java Question

How to interpret "public <T> T readObjectData(... Class<T> type)" in Java?

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
)?

Answer

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.