本文介绍了如何对instanceof List< MyType&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能得到这样的东西?我可以检查(obj instanceof List ),但是如果(obj instanceof List< MyType>) 。有没有一种方法可以做到这一点? 这是不可能的,因为在编译时删除数据类型的泛型。这样做的唯一可能的方式是编写某种类型的包装器来保存列表中包含的类型:

  public class GenericList< T>扩展ArrayList< T> 
{
private Class< T> genericType;

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

public Class< T> getGenericType()
{
return genericType;
}
}


How can I get this sort of thing to work? I can check if (obj instanceof List<?>) but not if (obj instanceof List<MyType>). Is there a way this can be done?

解决方案

That is not possible because the datatype erasure at compile time of generics. Only possible way of doing this is to write some kind of wrapper that holds which type the list holds:

public class GenericList <T> extends ArrayList<T>
{
     private Class<T> genericType;

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

     public Class<T> getGenericType()
     {
          return genericType;
     }
}

这篇关于如何对instanceof List&lt; MyType&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:32