1

I am not sure if this is a duplicate question to this one mainly because I'm a bit new to generics, so please be forgiving.

I have a generic class:

public class MyGeneric<T extends Collection>
{
    private Class<T> genericType;

    public MyGeneric()
    {
        // Missing code here
    }
}

My question is this: how do I initialize the genericType attribute? Basically, I need genericType to receive the Class object of whatever T is. If T is a LinkedList, I would like genericType to be equal to LinkedList.class.

Is this at all possible? Nothing I try seems to work.

Thanks, Isaac

Community
  • 1
  • 1
Isaac
  • 16,458
  • 5
  • 57
  • 81

1 Answers1

4

You're probably not going to like the answer, but you must pass it in yourself. So your constructor should be declared:

public MyGeneric(Class<T> genericType)
{
    this.genericType = genericType;
}

Due to type-erasure, the information is not available without being explicit like this.

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
  • Yeah I was starting to suspect that type-erasure may have something to do with it... Another set of eyes helped. Thanks! – Isaac Oct 14 '10 at 23:37