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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I was starting to suspect that type-erasure may have something to do with it... Another set of eyes helped. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.