如何实例化 Class来自T?
我有以下方法:
public <T> execute(HttpRequest request) {
...
// in parseAs i have to pass Class<T> how can I instantiate it from T?
request.execute().parseAs(classT);
}
PS: parseAs 是来自 Google http 客户端库。
I've got following method:
public <T> execute(HttpRequest request) {
...
// in parseAs i have to pass Class<T> how can I instantiate it from T?
request.execute().parseAs(classT);
}
PS: parseAs is method from google http client library.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能使用这些参数。
Java 的泛型使用一种称为类型擦除的东西 - 基本上所有这些
T
在运行时都变成Object
。因此,如果您确实需要知道这个T
是什么类,则需要传入一个Class
对象。这正是parseAs
> 正在做 - 要调用parseAs
,您需要调用parseAs(String.class)
。但是,您的
execute
没有Class
参数。因此,它不知道它是用什么专业化来调用的,因此无法将该数据传递给parseAs。解决方案是添加一个
Class
参数,并将其转至调用链中的下一个级别,其中具体类型(希望)是已知的:You cannot with those parameters.
Java's generics use something called type erasure - basically all those
T
s becomeObject
at runtime. So if you actually need to know what class thisT
is, you'll need aClass
object to be passed in. This is exactly whatparseAs
is doing - to invokeparseAs<String>
, you'd callparseAs(String.class)
.However, your
execute
has noClass
parameter. As such, it has no idea what specialization it was invoked with, and cannot therefore pass that data on toparseAs
.The solution is to add a
Class<T>
parameter and punt to the next level up in the call chain, where the concrete type is (hopefully) known: