Search code examples
javagenericstype-erasure

Type erasure, passing Class in argument


When I call:

ArrayList<MyType> myobject = new Gson().fromJson(data, new TypeToken<ArrayList<T>>(){}.getType());

everything works properly, using the fromJson(String, Type)
when I call:

ArrayList<MyType> myobject = helper(data);

public ArrayList<MyType> helper(String data){
    return new Gson().fromJson(data, new TypeToken<ArrayList<MyType>>(){}.getType());
}

it still works fine, but when I call :

ArrayList<MyType> myobject = helper(data, MyType.class);

public <T> ArrayList<T> helper(String data, Class<T> type){
    return new Gson().fromJson(data, new TypeToken<ArrayList<T>>(){}.getType());
}

the type argument is not proper.
How can I fix the last code snippet?

SOLUTION

As @LewsTherin proposed, I simply gave the exact Type in argument from caller
so helper declaration is so:

public <T> ArrayList<T> helper(String data, Type type){
    ArrayList<T> rtn = g.fromJson(data, type);
    return rtn;
}

and call like:

variable = helper(data, new TypeToken<ArrayList<MyType>>(){}.getType());

But if anybody can edit helper function to simplify the code, I will mark him as correct for sure!


Solution

  • I don't think it would work if you use in helper function. The solution might be to pass the type from the calling method. So it is clear what is happening.

    return new Gson().fromJson(data, new TypeToken<ArrayList<T>>(){}.getType());
    

    This is not actually specifying the object Class type. Hence why it doesn't work?