I am trying to use Generics and via Gson, trying to deserialize to type T. Following is my code.
public class Test<T> {
private final Subscriber<T> subscriber;
Gson gson = new Gson();
public interface Subscriber<T> {
public void onMessage(T message);
}
public Test(Subscriber<T> subscriber) {
this.subscriber = subscriber;
}
public void onResponse(CharSequence data) {
T responseObj = gson.fromJson(data.toString(), <how to get type of T here>);
subscriber.onMessage(responseObj);
}
}
As mentioned in the above code in method onResponse
, how can I deserialize to object of type T? I know we can pass the type in the constructor and maybe use it. But is there any other cleaner way? If not, I would prefer to leave it to the subscriber and do not use generics here.
Any thoughts? Thanks