[英]java.lang.ClassCastException: java.lang.Integer cannot be cast
[英]ClassCastException: java.lang.Object cannot be cast to java.lang.Integer
我的問題的根源是我有一個方法來處理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);
}
然后,在調用方法中......
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;
幫助將不勝感激。 我已經把我的大腦綁在了這個結上。
謝謝,
List#toArray()
返回一個Object
數組。 請改用List#toArray(T[])
。
Integer[] arg = (Integer[]) comps.toArray(new Integer[comps.size()]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.