Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get generic type of class at runtime

How can I achieve this?

public class GenericClass<T> {     public Type getMyType()     {         //How do I return the type of T?     } } 

Everything I have tried so far always returns type Object rather than the specific type used.

like image 685
Glenn Avatar asked Aug 04 '10 08:08

Glenn


People also ask

Is generic type information present at runtime?

Generic type information is not present at runtime.

How do you find a generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.

What is generic in runtime?

When a generic type is first constructed with a value type as a parameter, the runtime creates a specialized generic type with the supplied parameter or parameters substituted in the appropriate locations in the MSIL. Specialized generic types are created one time for each unique value type that is used as a parameter.

What is the generic class type called?

The type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.


1 Answers

As others mentioned, it's only possible via reflection in certain circumstances.

If you really need the type, this is the usual (type-safe) workaround pattern:

public class GenericClass<T> {       private final Class<T> type;       public GenericClass(Class<T> type) {           this.type = type;      }       public Class<T> getMyType() {          return this.type;      } } 
like image 123
Henning Avatar answered Sep 22 '22 20:09

Henning