Mehdi
Mehdi

Reputation: 107

get the typename of a class template

I want to get the typename of a class template (ex set). for example when i use :

Set<Personne> p = new HashSet<Personne>();
/* manipulate p etc ... */

How can I know the typename of p (which is Personne) using something like p.getTypeName() even if p is empty.

Upvotes: 2

Views: 681

Answers (2)

Chris Cashwell
Chris Cashwell

Reputation: 22859

You can't access the parameterized type at runtime because of Java's type erasure. If, however, you know what types it might be and just want to check if it is one of those:

if (someObject instanceof SomeType) {
    ...
} else if (someObject instanceof SomeOtherType) {
    ...
} ...

Upvotes: 1

NPE
NPE

Reputation: 500437

At runtime, you can't. This is due to type erasure.

Upvotes: 6

Related Questions