如何实现List <MyType>?

Tri*_*Man 75 java generics

我怎样才能让这种东西起作用?我可以检查是否,(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)

  • 你能举例说明一下吗 (3认同)

小智 25

if(!myList.isEmpty() && myList.get(0) instanceof MyType){
    // MyType object
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案并不安全,因为即使0元素是MyType,其他元素也可以是其他类型.例如,可能列表被声明为ArrayList <Object>,然后添加了MyType,然后添加了一个String. (3认同)
  • ...还有一个空清单?思考? (2认同)

eva*_*ong 8

您可能需要使用反射来获取要检查的类型.获取List的类型: 获取java.util.List的泛型类型

  • 据我所知,这仅适用于领域,但 +1 提及它。 (2认同)

Ivo*_*nov 8

如果您想检查它是不是空的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)