如何解读“public< T> T readObjectData(... Class< T>类型)"在Java中? [英] How to interpret "public <T> T readObjectData(... Class<T> type)" in Java?

查看:165
本文介绍了如何解读“public< T> T readObjectData(... Class< T>类型)"在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个Java代码。

  public< T> T readObjectData(ByteBuffer buffer,Class< T> type){
...
T retVal =(T)摘要;
返回retVal;

如何解释此代码?为什么我们需要 public< T> T 而不是 public T



如何将参数赋予第二个参数( Class< T> type )?

解决方案

code> readObjectData 方法generic,带有一个类型参数, T

  public< T> ... 

然后返回类型是 T

  ... T readObjectData(... 
$ b $

如果没有最初的< T> 这是泛型类型声明,则符号在参数列表中, Class< T> type 将会是未定义的。 是参数之一,因为返回类型和这个参数都引用 T ,这可以确保如果你传入 Class< String> code>,那么它将返回一个 String ,如果你传入一个 Class< Double> ,那么它会返回一个 Double 。



要传入参数,传入任何 Class 对象,例如 String.class


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

解决方案

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.

这篇关于如何解读“public&lt; T&gt; T readObjectData(... Class&lt; T&gt;类型)&quot;在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆