Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get base class's generic type parameter?

Tags:

I have three class as following:

public class TestEntity { }  public class BaseClass<TEntity> { }  public class DerivedClass : BaseClass<TestEntity> { } 

I already get the System.Type object of DerivedClass using reflection in runtime. How can I get the System.Type object of TestEntity using reflection?

Thanks.

like image 766
lucn Avatar asked Aug 23 '12 08:08

lucn


People also ask

How do you find the type of generic class?

You can get around the superfluous reference by providing a generic static factory method. Something like public static <T> GenericClass<T> of(Class<T> type) {...} and then call it as such: GenericClass<String> var = GenericClass. of(String. class) .

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.

How do I get a class instance of generic type T?

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.

What is a generic type parameter?

Generic Methods A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.


2 Answers

I assume that your code is just a sample and you don't explicitly know DerivedClass.

var type = GetSomeType(); var innerType = type.BaseType.GetGenericArguments()[0]; 

Note that this code can fail very easily at run time you should verify if type you handle is what you expect it to be:

if(type.BaseType.IsGenericType       && type.BaseType.GetGenericTypeDefinition() == typeof(BaseClass<>)) 

Also there can be deeper inheritance tree so some loop with above condition would be required.

like image 112
Rafal Avatar answered Dec 03 '22 22:12

Rafal


You can use the BaseType property. The following code would be resilient for changes in the inheritance (e.g. if you add another class in the middle):

Type GetBaseType(Type type) {    while (type.BaseType != null)    {       type = type.BaseType;       if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(BaseClass<>))       {           return type.GetGenericArguments()[0];       }    }    throw new InvalidOperationException("Base type was not found"); }  // to use: GetBaseType(typeof(DerivedClass)) 
like image 34
Eli Arbel Avatar answered Dec 03 '22 20:12

Eli Arbel