英文:
Expression expected fromJson method
问题
I don't know why I can't put T as a parameter in fromJson method.
public class AbstractResponseListener<T> implements Response.Listener<String> {
@Override
public void onResponse(String response) {
Gson gson = new Gson();
T abstractObject = gson.fromJson(response, T);
}
}
英文:
I don't know why I can't put T as parameter in fromJson method.
public class AbstractResponseListener<T> implements Response.Listener<String> {
@Override
public void onResponse(String response) {
Gson gson = new Gson();
T abstractObject = gson.fromJson(response, T);
}
}
答案1
得分: 1
在Java中,“传递类型”的唯一方式是传递其Class
对象。
有几个问题不允许你将T
作为方法的参数传递:
-
T
是类型,不是对象,因此不能作为参数传递(或存储到变量中,这几乎是相同的)。 -
即使前面的问题不存在,Java泛型的实现在一种称为类型擦除的方式上非常有限。简而言之,这意味着
T
的实际“值”(实际类型)仅在编译时(编译器执行类型检查并为某些调用添加类型转换)期间可用,但类型信息在运行时中被擦除,在编译后的代码中不可用。 -
fromJson()
方法的签名(其中之一,该方法有很多重载)是public <T> T fromJson(JsonElement json, java.lang.Class<T> classOfT) throws JsonSyntaxException
因此,它期望第二个参数是一个
Class
对象。可能的语法上正确的用法包括:gson.fromJson(response, String.class);
或
gson.fromJson(response, response.getClass());
查看更多检索类对象。
现在你知道为什么你不能做你试图做的事情了 :),你应该考虑你真正想要达到的目标。也许你是X-Y问题的受害者
英文:
The only way of "passing a type" in Java is to pass its Class
object.
There are several issues which do not allow you to pass T
as a parameter to a method:
-
T
is type, not an object, and as such cannot be passed as a parameter (or stored into a variable, which is virtually the same). -
Even if the previous problem were not present, Java implementation of generics is very limited in a way called type erasure. In short, it means that the actual "value" of of
T
(the actual type) is available only during compile type (and the compiler performs type checks and decorates some calls with typecasting), but the type information is erased from the compiled code and is not available in run time. -
The
fromJson()
method signature (one of the many possible ones, the method is heavily overloaded) ispublic <T> T fromJson(JsonElement json, java.lang.Class<T> classOfT) throws JsonSyntaxException
so it expects as the second parameter a
Class
object. The possible syntactically correct usage would be e.g.gson.fromJson(response, String.class);
or
gson.fromJson(response, response.getClass());
See more Retrieving Class Objects.
And now when you know why you cannot do what you are trying doing :), you should consider what you really want to reach. Maybe you're a victim of an X-Y problem
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论