Konstantin Komissarchik
Konstantin Komissarchik

Reputation: 29139

Any way to get a fully typed Class reference?

List.class is of type Class<List>. Note that List is referenced as a raw type. Since passing in a class is often used in generics method to determine the type parameter, is there a way to get a class object that fully specifies the type, such as Class<List<Integer>> or event Class<List<?>>?

Upvotes: 3

Views: 105

Answers (4)

ɲeuroburɳ
ɲeuroburɳ

Reputation: 7120

Other answers have already touched on the nature of erasures, etc... so I'll just include an example of how to get the reference:

@SuppressWarnings("unchecked")
Class<List<Integer>> cls = (Class<List<Integer>>)(Class)List.class;

Not the prettiest thing. But first you need to completely erase the type of List.class to just Class, then you can cast it to Class<List<Integer>>. At runtime its equivalent to the erased version of Class cls = List.class, but you'll get the compile time checks whenever you use the cls variable.

The @SuppressWarnings is required since you're doing bad things and you want to tell the compiler that you know that you are. Just how bad? Well... you have to be careful with the approach since you could have any class on the right-hand side, and the compiler won't care. You'll find the problems at runtime then. :)

Upvotes: 0

Konstantin Komissarchik
Konstantin Komissarchik

Reputation: 29139

It is possible to write a utility method for a particular parameterized class, such as a List.

public static <X> Class<List<X>> typedListClass( Class<X> type )
{
    return (Class) List.class;
}

Then this works fine:

Class<List<Integer>> cl = typedListClass( Integer.class )

Upvotes: 0

Adrian
Adrian

Reputation: 46532

No (see JB's answer), however, you can use class.getTypeParameters() to find out: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getTypeParameters()

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691943

No. At runtime, List<Integer>, List<Object> and List are the same type, due to type erasure.

Upvotes: 8

Related Questions