More Than Five
More Than Five

Reputation: 10419

Getting the .class of a parameterised type?

If a List and want to get the class of that rather than List, I cant't do

List.class

I can't do

List<TennisBall>.class

The reason I want to do this is I am using an annotation which excepts Class which generates documentation. I can express the parameterised class.

Any tips

Upvotes: 0

Views: 43

Answers (2)

tbsalling
tbsalling

Reputation: 4545

Generics ensure typesafety at compile-time, but were also designed to avoid overhead at runtime. Therefore the Java compiler applies "type erasure" - which means that information about generics is not written into the .class files.

I can recommend to read this article from Baeldung.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074238

Remember that generics are 99% a compile-time construct. Generics don't create new classes/interfaces. Both List (the raw type) and List<TennisBall> (the parameterized type) are represented by the same class, which is List.class. (And the implementation of a class is similarly shared: LinkedList and LinkedList<TennisBall> are both implemented by the same class.)

You'll need to refer to the annotation's documentation to see what to do about generics with that tool when what you want it to document involves a generic type parameter.

Upvotes: 1

Related Questions