0

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);
    }
}
  • Because [generics get erased](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html). Also, method [`Gson.fromJson(...)`](https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/Gson.html#fromJson(java.lang.String,java.lang.Class)) expects a `String` and a `Class`-object. `T` is not a `Class`-object. – Turing85 Aug 02 '20 at 13:10
  • `T` is a _type_. You also cannot use `Object` or `String` or whatever as the argument to the `fromJson` method. It needs a _class object_! – Seelenvirtuose Aug 02 '20 at 13:11
  • In this code snippet, the type parameter `T` does not make any sense. You are not doing anything with it! Did you mean `class AbstractResponseListener implements Response.Listener` and `String abstractObject = gson.fromJson(response, String.class)`? – Seelenvirtuose Aug 02 '20 at 13:16

1 Answers1

1

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:

  1. 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).

  2. 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.

  3. The fromJson() method signature (one of the many possible ones, the method is heavily overloaded) is

    public <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 :)

Honza Zidek
  • 9,204
  • 4
  • 72
  • 118