文本文件中有两个数据。我试图将它们检索出来,但出现以下错误
########## Error with java.lang.ClassCastException:
java.util.ArrayList cannot be cast to [Ljava.lang.Object; ##########
Size 1
代码
try {
File file = new File(filePath + "ABC.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
List list = new ArrayList();
try {
while ((st = br.readLine()) != null) {
String id = st.substring(92, 100);
try {
list.add(getDetail(id));
} catch (Exception e) {
e.printStackTrace();
}
for (Object[] o : (List<Object[]>) list) {
Details x = new Details();
x.setType(o[0].toString());
....
}
}
br.close();
} catch (Exception ex) {
logger.printError(Reader.class, "Error with " + ex);
}
logger.printInfo(Reader.class, "Size " + list.size());
} catch (IOException ex) {
ex.printStackTrace();
}
查询
public List getDetail(int id){
StringBuilder bf = new StringBuilder();
bf.append("SELECT ");
bf.append("'ABC', ");
....
return em.createQuery(bf.toString()) .getResultList();
}
接下来我可以尝试什么?
使用泛型类型:
List<Details> list = new ArrayList<>();
try {
while ((st = br.readLine()) != null) {
String id = st.substring(92, 100);
try {
list.addAll(getDetail(id)); // add all results
} catch (Exception e) {
e.printStackTrace();
}
}
br.close();
} catch (Exception ex) {
logger.printError(Reader.class, "Error with " + ex);
}
您的
getDetail
方法应返回转换为详细信息列表的行
public List<Details> getDetail(int id){
// prepare your query
StringBuilder bf = new StringBuilder();
bf.append("SELECT ");
bf.append("'ABC', ");
// iterate over search results and convert each row into Details
List<Details> results = new ArrayList<>();
ResultSet rs = stmt.executeQuery(bf.toString());
while (rs.next()) {
results.add(toDetails(rs)); // convrt single row to Details model
}
return results;
}
将单个结果行转换为
Details
:
private Details toDetails(ResultSet rs){
Details x = new Details();
x.setType(rs.getString(0));
...
return x;
}
这个问题似乎与 Query API 有关。
所以在这里,我建议使用类似
public List<Object[]> getDetail(int id){
StringBuilder bf = new StringBuilder();
bf.append("SELECT ");
bf.append("'ABC', ");
....
return em.createQuery(bf.toString()) .getResultList(); -- getResultList returns List.
}
然后
List<Object[]> list=new Arraylist<Object[]>();
.....
list.addAll(getDetail(id)); -- as we are adding collection here.
而不是
list.add(getDetail(id));
原始代码。
欲了解更多信息,您可以参考现有的SO帖子