Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a generic Class<T> as an argument

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

like image 655
znat Avatar asked Aug 21 '12 15:08

znat


People also ask

Can I pass a class as an argument Java?

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.

What does T stand for in generics?

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

How do you pass a generic object in Java?

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);

What is generic type arguments?

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.


1 Answers

Thanks to Java Type Erasure, you can't.

http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

like image 56
Joe Avatar answered Sep 28 '22 00:09

Joe