我怎样才能让这种东西起作用?我可以检查是否,(obj instanceof List<?>)但不是(obj instanceof List<MyType>).有没有办法可以做到这一点?
Mar*_*aux 44
这是不可能的,因为在泛型编译时数据类型擦除.只有这样做的可能方法是编写某种包含列表所包含类型的包装器:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 25
if(!myList.isEmpty() && myList.get(0) instanceof MyType){
// MyType object
}
Run Code Online (Sandbox Code Playgroud)
如果您想检查它是不是空的object实例,则可以使用List<T>它:
if(object instanceof List){
if(((List)object).size()>0 && (((List)object).get(0) instanceof MyObject)){
// The object is of List<MyObject> and is not empty. Do something with it.
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
if (list instanceof List && ((List) list).stream()
.noneMatch((o -> !(o instanceof MyType)))) {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
76632 次 |
| 最近记录: |