如何解释“公共<T>T readObjectData(... Class<T> type)";在爪哇? [英] How to interpret "public <T> T readObjectData(... Class<T> type)" in Java?
问题描述
我有这个 Java 代码.
I have this Java code.
public <T> T readObjectData(ByteBuffer buffer, Class<T> type) {
...
T retVal = (T) summaries;
return retVal;
如何解释这段代码?为什么我们需要 public <T>T
而不是 public T
?
How to interpret this code? Why do we need public <T> T
instead of public T
?
如何将参数赋予第二个参数(Class
)?
How to give the parameter to the 2nd argument (Class<T> type
)?
推荐答案
这声明了 readObjectData
方法的泛型,带有一个类型参数 T
.
This declares the readObjectData
method generic, with one type parameter, T
.
public <T> ...
那么返回类型是T
.
... T readObjectData(...
如果没有作为泛型类型声明的初始
,符号 T
将是未定义的.
Without the initial <T>
, which is the generic type declaration, the symbol T
will be undefined.
在参数列表中,Class
是参数之一.因为返回类型和这个参数都引用了T
,这就保证了如果你传入一个Class
,那么它会返回一个String
>.如果你传入一个 Class
,那么它会返回一个 Double
.
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
.
要传入参数,传入任何 Class
对象,例如String.class
.
To pass in the parameter, pass in any Class
object, e.g. String.class
.
这篇关于如何解释“公共<T>T readObjectData(... Class<T> type)";在爪哇?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!