开发者

Retrieving the Class object of the generic argument

开发者 https://www.devze.com 2023-01-19 21:42 出处:网络
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 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消