Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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

like image 925
prosseek Avatar asked Apr 08 '13 20:04

prosseek


People also ask

What is class T type in Java?

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.

What does <? Super t mean in Java?

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 .

What does T stand for in Java generics?

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.

What does T class mean?

Q - Economy/Coach Discounted. R - First Class Suite or Supersonic (discontinued) S - Economy/Coach. T - Economy/Coach Discounted.


2 Answers

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.

like image 130
rgettman Avatar answered Oct 02 '22 09:10

rgettman


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 
like image 44
cdhowie Avatar answered Oct 02 '22 08:10

cdhowie