我怎样才能让这类东西工作呢?我可以检查是否为(obj instanceof List<?>)
,但无法检查是否为(obj instanceof List<MyType>)
。有没有办法做到这一点?
发布于 2012-04-11 22:36:53
这是不可能的,因为泛型的数据类型在编译时会被擦除。要做到这一点,唯一可能的方法是编写某种类型的包装器,其中包含列表包含的类型:
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;
}
}
发布于 2016-07-23 16:46:02
if(!myList.isEmpty() && myList.get(0) instanceof MyType){
// MyType object
}
发布于 2012-04-11 22:40:53
您可能需要使用反射来检查它们的类型。要获取列表的类型:Get generic type of java.util.List
https://stackoverflow.com/questions/10108122
复制相似问题