generic types and class.getName()
I am wondering how to obtain a name of a generic type.
Something along these lines:
class Foo<T> {
void method() {
String typeName=T.class.getName();
}
}
This, obviously, doesn't work. I poked around Class<T> and such, but couldn't find a simple solution. Any ideas?
[329 byte] By [
kuzmicha] at [2007-10-3 4:07:43]

> I am wondering how to obtain a name of a generic
> type.
You can't. It's sad, but it can't be done.
During compile, generic types are transformed into non-generics with a process called "erasure". "Erasure" means that the generic data is erased from the class an only some typecasts remains. This keeps generics compatible with older jvms. But (and there's always a but), this also keeps us from knowing the generic type - It's important to understand that during runtime this information simply does not exist.
It's sad, but generics are not C++ templates.
I think I understand your point, but I can't figure out why this would prohibit doing something like T.class.getName(). If the "erasure" process essentially substitutes T for some concrete MyClass, then the statement should be perfectly valid.
You don't understand.
T doesn't exist at runtime. The compiler erased it.
The class Foo does not retain any information about T after the compilation is done.
It's like T never existed. You just have Foo. That's all. Nothing else.
T is used ONLY by the compiler to do some additionnal type check validations.
Then it is erased. Gone. Bye bye.
So how the "evaluation" of T.class could be possible at runtime?