Dacav
Dacav

Reputation: 14098

Getting the .class of a generic class

Suppose you have a certain class C, which supports generics (so C<X> defines a type). I would like to do something like:

I'd like to obtain an instance of the Class<C<X>> class. I would say that this can be obtained through the following expression:

C<X>.class

But the compiler doesn't agree with me on that :P

Any hint?

Upvotes: 2

Views: 123

Answers (2)

Natix
Natix

Reputation: 14257

This is not possible because of type erasure. The type parameters are not available at runtime - all the instances of C<Whatever> are actually instances of simply C. Therefore, you can only write a class literal like C.class.

However, if you subclass a generic class with defining a concrete type parameter, such as this:

class StringC extends C<String> {}

... it is actually possible to obtain the value of the type parameter (which is String) via reflection. See these blogs:

Upvotes: 7

Peter Lawrey
Peter Lawrey

Reputation: 533870

The closest you can get is

@SuppressWarning("unchecked")
Class<C<X>> cxClass = (Class<C<X>>) (Class) C.class

As generics are a compile time feature, this doesn't really do much as you can see.

Upvotes: 7

Related Questions