使用迭代器或for循环获取类强制转换异常

时间:2013-09-03 09:11:23

标签: java iterator hashmap

我有一个列表,我需要迭代它,即使在使用Iterator或for循环后它给我类抛出异常,给我的问题是

代码如下,

List<DataLoaderIndex> dataList = new ArrayList<DataLoaderIndex>();

dataList = dataLoaderIndexDAO.getDataSourceStatus(uploadFrequency,reportEndDate);

Map<String,String> mapData = new HashMap<String,String>();

Iterator<DataLoaderIndex> itrObj = dataList.iterator();
            while (itrObj.hasNext()) {
                DataLoaderIndex dlObj = itrObj.next();
                String dsName = dlObj.getDataSourceType();
                    String dsStatus = dlObj.getStatus();
                    mapData.put(dsName, dsStatus);

            }

/*for(int i=0;i<dataList.size();i++){
             String dsName = dataList.get(i).getDataSourceType();
             String dsStatus = dataList.get(i).getStatus();
             mapData.put(dsName, dsStatus);
         }*/

DAO部分在这里:

public List<DataLoaderIndex> getDataSourceStatus(String uploadFrequency,String reportEndDate){


    List<DataLoaderIndex> dataList = null;
    if(session!=null){
        Query query = session.createQuery("select dataSourceType,uploadedBy,status from DataLoaderIndex where DATE (reportEndDate) =:endate and UPPER(reportFreq) = UPPER(:uploadFreq)");  
        query.setString("endate", reportDate);
        query.setString("uploadFreq", uploadFrequency);
        dataList = query.list();
    }

    return dataList;
}

我的行

异常
String dsName = dlObj.getDataSourceType(); 

...

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.work.in.synct.entity.DataLoaderIndex
    at com.work.synct.service.dataloaderimpl.DataUploadDetailsService.getUploadStatus(DataUploadDetailsService.java:36)

1 个答案:

答案 0 :(得分:0)

DAO方法中,应使用TypedQuery强类型地查询查询。由于此时未输入查询,因此返回List<Object[]>,由于类型擦除,可以将其分配给dataList。在运行时List<DataLoaderIndex>会丢失其类型信息,因此可以为其分配List<Object[]>

List<DataLoaderIndex> dataList = null;
if(session!=null){
    TypedQuery<DataLoaderIndex> query = session.createQuery("select dataSourceType," +
        "uploadedBy,status from DataLoaderIndex where DATE " +
           " (reportEndDate) =:endate and UPPER(reportFreq) = UPPER(:uploadFreq)", 
              DataLoaderIndex.class);


    query.setString("endate", reportDate);
    query.setString("uploadFreq", uploadFrequency);
    dataList = query.list();
}

return dataList;

<强>更新

我刚刚意识到你没有使用JPA。而是尝试在DAO方法中强制转换返回的列表。在某些时候,您需要向上转换为List<DataLoaderList>

类型

dataList = (List<DataLoaderList>)query.list();