在列表中键入Cast对象



我有一个列表,正在尝试添加一些自定义类类型的成员。

List<MyCustomClass> myList = new ArrayList<MyCustomClass>();
myList.addAll(queryResponse.getRecords());

实际上CCD_ 1又是一个具有2个成员的自定义类;

private Long totalRecords;
private List<T> records;

我的问题是,我想把myList(即queryResponse.getRecords())的单个成员选为MyCustomClass

一旦执行查询,它们在运行时就属于"Object"类型。

我该怎么做?

假设queryResponse.getRecords()返回Object,您可以像下面的一样键入种姓

myList.addAll((MyCustomClass)queryResponse.getRecords());
myList.addAll((List)queryResponse.getRecords());

应该工作,产生一个类型的安全警告。通过这样做,您可以绕过编译时类型的安全保证,因此您可以确保以后不会出现ClassCastException。

关于:

List<MyCustomClass> myList = new ArrayList<MyCustomClass>();
for (Object element : queryResponse.getRecords()) {
    if (element instanceof MyCustomClass) {
        // this will never fail because of the check above
        myList.add((MyCustomClass)element);
    }
    else {
        // do something here in case element has the wrong type
        System.err.println("Found incompatible record!");
    }
}

这使用instanceof运算符来确保强制转换不会失败。当对象的类型不兼容时,您到底要做什么取决于您的需求。

最新更新