I need to pass a 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 e.g. something.class
...
}
}
Thanks
We have a method coypObject() which accepts an object of the current class and initializes the instance variables with the variables of this object and returns it. In the main method we are instantiating the Student class and making a copy by passing it as an argument to the coypObject() method.
< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.
Generics Work Only with Reference Types: When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char. Test<int> obj = new Test<int>(20);
The generic argument list is a comma-separated list of type arguments. A type argument is the name of an actual concrete type that replaces a corresponding type parameter in the generic parameter clause of a generic type. The result is a specialized version of that generic type.
Thanks to Java Type Erasure, you can't.
http://docs.oracle.com/javase/tutorial/java/generics/erasure.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With