Understanding generic types in Java

I have a general class that says:

@H_ 404_ 8@

@H_ 404_ 8@

MyClass<T>@H_419_12@ 
 

在这个类的方法中,我想测试T的类型,例如:@H_404_8@

@H_404_8@

void MyMethod()
{

    if (T == String)
        ...
    if (T == int)
        ...
}@H_419_12@ 
 

我怎样才能做到这一点 ?@H_404_8@

谢谢你的帮助@H_404_8@

Solution

In general, you cannot because of type erasure For details, see Angelika Langer's Java genetics FAQ

@H_ 404_ 8@

What you can do is pass a class < T > into your constructor, and then check: @ h_ 404_ 8@

@H_ 404_ 8@

public MyClass<T>
{
    private final Class<T> clazz;

    public MyClass(Class<T> clazz)
    {
        this.clazz = clazz;
    }

    public void myMethod()
    {
        if (clazz == String.class)
        {
           ...
        }
    }
}@H_419_12@ 
 

请注意,Java不允许将基元用于类型参数,因此int不在…@H_404_8@

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>