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]
# 1

> 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.

Zaph0da at 2007-7-14 22:07:25 > top of Java-index,Core,Core APIs...
# 2
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.
kuzmicha at 2007-7-14 22:07:25 > top of Java-index,Core,Core APIs...
# 3

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?

jfbrierea at 2007-7-14 22:07:25 > top of Java-index,Core,Core APIs...