Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...