Anyone know how I go about getting the class of a generic type e.g. I'd
like to be able to do the following:
Class clazz = T.getClass();
Seems a strange request, but without going into detail, I need to be
able to do this. I don't have access to an instance of type T and do
not want to pass an instance in either. In fact, I need to create an
instance of type T inside of a class paramaterised with type T.
many thanks in advance.
Oliver Wong - 10 Feb 2006 19:03 GMT
> Anyone know how I go about getting the class of a generic type e.g. I'd
> like to be able to do the following:
>
> Class clazz = T.getClass();
Not possible. The generic type information is erased at runtime.
> Seems a strange request, but without going into detail, I need to be
> able to do this. I don't have access to an instance of type T and do
> not want to pass an instance in either. In fact, I need to create an
> instance of type T inside of a class paramaterised with type T.
>
> many thanks in advance.
The solution I've most commonly seen is to pass in an instance of
Class<T>.
E.g.
String foo = makeMeThisObject(String.class);
- Oliver
JavaEnquirer - 12 Feb 2006 12:01 GMT
> The solution I've most commonly seen is to pass in an instance of
> Class<T>.
[quoted text clipped - 4 lines]
>
> - Oliver
Cheers Oliver, I feared that I'd have to do that, though, fear is too
strong a word!!!
Roedy Green - 10 Feb 2006 21:31 GMT
On 10 Feb 2006 09:55:56 -0800, "JavaEnquirer"
<javaenquirer@hotmail.co.uk> wrote, quoted or indirectly quoted
someone who said :
>Seems a strange request, but without going into detail, I need to be
>able to do this. I don't have access to an instance of type T and do
>not want to pass an instance in either. In fact, I need to create an
>instance of type T inside of a class paramaterised with type T.
the problem is type erasure. All record of what T was is gone by run
time. T is usually just an Object by then.

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.