How to Get the Type of T from a Member of a Generic Class or Method

How to get the type of T from a member of a generic class or method

If I understand correctly, your list has the same type parameter as the container class itself. If this is the case, then:

Type typeParameterType = typeof(T);

If you are in the lucky situation of having object as a type parameter, see Marc's answer.

How to get type of T generic?

You can use typeof to get the type of a generic parameter: typeof(T)

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. I suggest reading the chapter about type erasure in the Java Tutorial for more details.

A popular solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.

class Foo<T> {
final Class<T> typeParameterClass;

public Foo(Class<T> typeParameterClass) {
this.typeParameterClass = typeParameterClass;
}

public void bar() {
// you can access the typeParameterClass here and do whatever you like
}
}

How to find out type of generic parameter T if it was passed as an Interface?

You can get the Type that represents T, and use the IsInterface property:

Type type = typeof(T);
if (type.IsInterface) {
...
}

If you want to know which interface is passed, just use == to compare the Type objects, e.g.

if (typeof(T) == typeof(IConvertible))

Generic type where T is derived from a generic type

You can do this by creating a class that is not generic like the following

public abstract class Foo { }
public abstract class Foo<T> : Foo { }

And now you can use your constrain with Foo

public class Bar<T> where T : Foo { }

And this will be required to T be a type of Foo and as long as you derive generic Foo<> from non-generic Foo your T must be Foo<T>

Example of usage:

public abstract class Foo { }
public abstract class Foo<T> : Foo { }
public abstract class Boo : Foo<string> { }

public class Bar<T> where T : Foo { }

public class BarTest : Bar<Boo> { }

How to access a class member for a class of generic type?

An ideal way would be for your generic class to extend an interface. If you already know that every object of the generic class has an id, declare <O extends Identifiable where Identifiable would be something of the likes :

public interface Identifiable {
int getId();
}

If you can't have the generic class extending an Interface, try using reflection.



Related Topics



Leave a reply



Submit