I have a class like this:
public class Test<T>{
public Test() {
// TODO : get the actual type of T
}
}
Test<String> a = new Test<String>();
// could I write code like this? How to get the type of T which is
String here in Test's constructor
CD1 - 26 Jul 2007 14:22 GMT
Hi,
You can't get the type of T in runtime. Why do you want to know this?
See ya!
On Jul 26, 10:12 am, "joeh...@gmail.com" <joeh...@gmail.com> wrote:
> I have a class like this:
> public class Test<T>{
[quoted text clipped - 8 lines]
> // could I write code like this? How to get the type of T which is
> String here in Test's constructor
Roedy Green - 26 Jul 2007 14:35 GMT
>// could I write code like this? How to get the type of T which is
>String here in Test's constructor
You can't. This was done on purpose and is called "type erasure". T is
a purely compile time notion. All trace of it is erased from the
object file, so there is nothing for the rune time to get a grip on.

Signature
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
joehust@gmail.com - 26 Jul 2007 14:47 GMT
On Jul 26, 9:35 pm, Roedy Green <see_webs...@mindprod.com.invalid>
wrote:
> >// could I write code like this? How to get the type of T which is
> >String here in Test's constructor
[quoted text clipped - 5 lines]
> Roedy Green Canadian Mind Products
> The Java Glossaryhttp://mindprod.com
Thank you for replying. I understand it now.
Lew - 26 Jul 2007 14:52 GMT
> I have a class like this:
> public class Test<T>{
[quoted text clipped - 7 lines]
> // could I write code like this? How to get the type of T which is
> String here in Test's constructor
One trick in the literature is to pass in or create a Class<T> member of the
class to use as a type marker.
I don't remember where I've read this, but a quick googling should turn up
several examples.

Signature
Lew
Piotr Kobzda - 26 Jul 2007 23:22 GMT
>> I have a class like this:
>> public class Test<T>{
[quoted text clipped - 10 lines]
> One trick in the literature is to pass in or create a Class<T> member of
> the class to use as a type marker.
Another trick is to create an instance that way:
Test<String> a = new Test<String>() {};
and then, in Test's constructor do:
Class<T> actualTypeOfT = (Class<T>)
((ParameterizedType)getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
Usually I use a first trick. But that's sometimes useful to know actual
type argument without explicitly passing it to the generic class.
piotr