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

Lur*_*k21 12 java classcastexception

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

我发现我不能简单地将ResultSet传递回调用方法,因为关闭了ResultSet,然后任何使用它的尝试都会产生一个已经关闭的错误.

因此,在关闭资源之前,我遍历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);
            }
Run Code Online (Sandbox Code Playgroud)

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

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

        ...
    }
Run Code Online (Sandbox Code Playgroud)

我得到:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
Run Code Online (Sandbox Code Playgroud)

帮助将不胜感激.我已经把我的大脑绑在了这个结上.

谢谢,

Per*_*ror 33

List#toArray()返回一个Object数组.请List#toArray(T[])改用.

Integer[] arg = (Integer[]) comps.toArray(new Integer[comps.size()]);
Run Code Online (Sandbox Code Playgroud)

  • 圣洁吸烟你很快.谢谢你做到了.好极了!我再次前进!! 谢谢你,谢谢你,谢谢你. (2认同)
  • 我认为参数应该是`new Integer [0]` - 你实际上并不需要传入的对象中的任何空间,它只用于获取类信息,但你必须实例化它. (2认同)