Getting the class from a type parameter

C

Cherukan

If I have a Class parameter, I can get the type of the parameter and
use it.

void method(Class<T> clazz)
{
Map<String, T> t = new HashMap<String, T>();

}

Is there any way to do the reverse, i.e. with a type variable, is there
a way
to get the Class ?

void <T> method(T t) {
Class<T> clazz = T.class; // does not work

Class<T> clazz = t.getClass(); // works, but only if t is not null
}

Thx
 
J

Jeroen V.

Cherukan said:
Is there any way to do the reverse, i.e. with a type variable, is there
a way
to get the Class ?

void <T> method(T t) {
Class<T> clazz = T.class; // does not work

Class<T> clazz = t.getClass(); // works, but only if t is not null
}

Thx

The "class of a type variable" is a Class instance representing the
*runtime* (class)type of the variable. This means that null has no Class
since it has no runtime type. I don't think there is a way to get the
static type of a variable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top