将对象转换为短

时间:2012-04-24 15:16:04

标签: java object type-conversion classcastexception

我想将Object转换为Short。我的代码是这样的:

List<Batch> lsMaxBatch = em.createNativeQuery(sqlMaxBatch).getResultList();
Iterator iter = lsMaxBatch.iterator();
while (iter.hasNext()) {
    Short batchId = Short.valueOf(iter.next() + "");
    ls.add(batchId);
}

可以吗?

因为如果我这样做转换:

Short batchId = (Short) iter.next();

我收到错误:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java.lang.Short

感谢

1 个答案:

答案 0 :(得分:4)

像这样的无类型查询会返回List<Object[]>。异常消息提示:[Ljava.lang.Object; cannot be cast...

修复您的代码:

List<Object[]> lsMaxBatch = em.createNativeQuery(sqlMaxBatch).getResultList();
Iterator<Object[]> iter = lsMaxBatch.iterator();
while (iter.hasNext()) {
    Object[] row = iter.next();
    Short batchId = (Short) row[0];
    ls.add(batchId);
}

是的,让List<Object[]>很糟糕。要改善这一点,请使用EntityManager query creation methods之一返回TypedQuery<T>