ClassCastException: java.lang.Object无法转换为java.lang.Integer

13
我的问题根源在于我有一个处理JDBC查询并在查询后释放所有连接的方法。"ResultSet"被传回调用方法。

我发现不能简单地将ResultSet传回调用方法,因为ResultSet关闭后,任何试图使用它的尝试都会得到一个Already Closed错误。

因此,在关闭资源之前,我遍历ResultSet并将其存储在ArrayList中。

由于该方法处理任何查询,我不知道返回的是什么类型。因此,ArrayList存储通用的s。

这个方法有效,除了一个表中的一个字段..在一个数据库中,它是一个Integer[]字段。

我得到了一个JDBC4Array对象,我花了很长时间才将其转换为一个Integer[]以存储在ArrayList中。我确实需要它是一个Integer[]。

这就是我现在拥有的...经过许多沮丧的banjaxxing之后。

在遍历ResultSet时,在连接关闭之前,我做了这个:

            // For every row in the ResultSet
            while (rs.next()) {
                // Initialize a ITILRow for this ResultSet row
                ITILRow row = new ITILRow();

                // For each column in this row, add that object to the ITILRow
                for (int colNum=1; colNum<=numCols; colNum++) {
                    Object o = rs.getObject(colNum);

                    // JDBC4Array is a real pain in the butt
                    ArrayList<Integer> tmpList = new ArrayList<Integer>();
                    if (o != null) {
                        if (o.getClass().getSimpleName().endsWith("Array")) {
                            // At least at this time, these Arrays are all Integer[]
                            Array a = (Array) o;
                            Integer[] ints = (Integer[]) a.getArray();
                            for (Integer i : ints) {
                                tmpList.add(i);
                            }
                            o = tmpList;
                        }
                    }

                    row.add(o);
                }

                // Add the ITILRow to allRows
                allRows.add(row);
            }

然后,在调用的方法中...

    for (ITILRow row : allRows) {
        ...
        ArrayList comps = (ArrayList) row.getObject(5);
        Integer[] argh = (Integer[]) ((ArrayList<Integer>) comps).toArray();

        ...
    }

然后我得到:

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

需要帮助,这个问题让我思维混乱。

谢谢。

1个回答

34

2
哇塞,你真快。谢谢,解决了。耶!我又可以继续前进了!!非常感谢你。 - Lurk21
2
我认为参数应该是 new Integer[0] -- 实际上你不需要在传递的对象中使用任何空间,它只用于获取类信息,但你必须实例化它。 - AgilePro
如果传递的数组足够大(至少有comps.size()个元素),则传递的数组将被填充并由toArray方法返回。使数组足够大将防止创建另一个相同类型的数组。 - jarnbjo
哦,那很有道理。然后,是的,最好制作一个确切大小的“新”对象。但是,上面缺少了“new”。 - AgilePro
1
这种方式强制转换为(Integer[])甚至是多余的。好的解决方案! - Hibbem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接