tags:

views:

26

answers:

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

+4  A: 

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
Yeah I was starting to suspect that type-erasure may have something to do with it... Another set of eyes helped. Thanks!
Isaac