How to get the actual type of T

J

joehust

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
 
R

Roedy Green

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

joehust

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.

Thank you for replying. I understand it now.
 
L

Lew

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

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

Piotr Kobzda

Lew said:
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
 

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
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top