Passing the general class <T> as an argument
I need to pass the class as an argument, but I only have the generic type T. How can I infer the generic class and pass it to fromJson() ?
public class Deserializer<T> implements JsonDeserializer<JsonList<T>> { public T someMethod(){ ... T tag = gson.fromJson(obj, ???); // takes a class eg something.class ... } } thanks
+6
3 answers
Assuming Deserializer is your class, a typical way to do this is to take Class as a constructor parameter:
public class Deserializer<T> implements JsonDeserializer<JsonList<T>> { public static <T> Deserializer<T> newInstance(Class<T> c) { return new Deserializer<T>(c); } private final Class<T> clazz; private Deserializer(Class<T> c) { this.clazz = c; } public T someMethod(){ ... T tag = gson.fromJson(obj, clazz); // takes a class eg something.class ... } } Then in the client code:
Deserializer<String> d = Deserializer.newInstance(String.class); +2
Thanks to the Java Type Erasure style, you cannot.
http://docs.oracle.com/javase/tutorial/java/generics/erasure.html
+6