Generics and type erasure

Discussion in 'Java' started by Martin Lorentzson, Nov 5, 2006.

  1. 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
     
    Martin Lorentzson, Nov 5, 2006
    #1
    1. Advertising

  2. Martin Lorentzson

    Daniel Pitts Guest

    Martin Lorentzson wrote:
    > 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.
     
    Daniel Pitts, Nov 5, 2006
    #2
    1. Advertising

  3. "Daniel Pitts" <> writes:

    > 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.
     
    Martin Lorentzson, Nov 6, 2006
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Sebastian Millies

    Java Generics, Type Erasure and Frameworks

    Sebastian Millies, Oct 7, 2004, in forum: Java
    Replies:
    1
    Views:
    670
    Chris Uppal
    Oct 7, 2004
  2. z-man
    Replies:
    8
    Views:
    400
    Thomas Weidenfeller
    Oct 9, 2006
  3. William
    Replies:
    5
    Views:
    1,073
  4. William
    Replies:
    3
    Views:
    696
    Andreas Leitgeb
    Mar 4, 2011
  5. Marcin Pietraszek

    Java generics and type erasure

    Marcin Pietraszek, May 23, 2011, in forum: Java
    Replies:
    29
    Views:
    1,101
Loading...

Share This Page