Generics and type erasure

  • Thread starter Martin Lorentzson
  • Start date
M

Martin Lorentzson

I would like to determine the class value of a generic type. Is it
possible?

Right now, I'm passing the type as a parameter to the class
constructor:

public class Example<T extends Enum<T>> {

private final Class<T> clazz;

protected Example(Class<T> clazz) {
this.clazz = clazz;
}

public T parse(String text) {
// Can I derive the value of clazz from T?
T value = T.valueOf(clazz, text);
return value;
}
}

But I'm wondering if I can derive the class value of T instead of
using a constructor parameter or is type erasure as play here?

/Martin
 
D

Daniel Pitts

Martin said:
I would like to determine the class value of a generic type. Is it
possible?

Right now, I'm passing the type as a parameter to the class
constructor:

public class Example<T extends Enum<T>> {

private final Class<T> clazz;

protected Example(Class<T> clazz) {
this.clazz = clazz;
}

public T parse(String text) {
// Can I derive the value of clazz from T?
T value = T.valueOf(clazz, text);
return value;
}
}

But I'm wondering if I can derive the class value of T instead of
using a constructor parameter or is type erasure as play here?

/Martin

In fact, you cannot. That is the whole point(problem) of erasure.
Even the EnumMap and EnumSet classes require a Class object in their
construction.
 
M

Martin Lorentzson

Daniel Pitts said:
In fact, you cannot. That is the whole point(problem) of erasure.

OK, I thought I figured as much from the docs but I just wanted to
make sure. Thanks.
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top