如何转换对象数组?
我是 java 新手,正在使用 netbeans 探索 java ee 应用程序。
我有代码:
Userbean 中的方法:
public List userList() {
Query q = em.createNativeQuery("select username,address from tbuser");
Iterator i = q.getResultList.iterator;
ArrayList<UserState> userinfo = new ArrayList<UserState>();
while (i.hasNext()) {
Vector result = (Vector) i.next(); // <- HERE
UserState us = new UserState();
us.setName((String) result.get(0));
us.setAddress((String) result.get(1));
userinfo.add(us);
}
return userinfo;
}
我使用此方法来构造 jsf 数据表,并与 netbeans6.5 和 glassfish2 一起正常工作,
但是当我使用相同的方法时,除了将向量更改为 netbean 6.9
和 glassfish 3 中的 arraylist 外,我得到了该类 抛出
运行时
异常:对象无法转换为 java.util.list;有人知道该怎么做吗?谢谢..
I am new to java and exploring java ee application with netbeans.
I have the code :
Method in userbean:
public List userList() {
Query q = em.createNativeQuery("select username,address from tbuser");
Iterator i = q.getResultList.iterator;
ArrayList<UserState> userinfo = new ArrayList<UserState>();
while (i.hasNext()) {
Vector result = (Vector) i.next(); // <- HERE
UserState us = new UserState();
us.setName((String) result.get(0));
us.setAddress((String) result.get(1));
userinfo.add(us);
}
return userinfo;
}
I use this method to construct jsf datatable and work fine with netbeans6.5 and glassfish2
however when i use the same method except i change the vector to arraylist in netbean 6.9
and glassfish 3 i got the class cast
exception at run time: object cannot be cast to java.util.list;
Does anybody know how to do it? thank you..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我怀疑代码是否像这样工作,诸如
hasNext()
之类的方法缺少括号。如果您复制了代码,请再次复制,因为让我们猜测您的代码不会提高答案的质量。您的问题是您想要访问 Vector 中的元素。但Vector内部的对象类型不是Vector,而是一种不同类型的集合。您想要检索此 Vector 的一个元素(这完全没问题),但随后尝试将其转换为
Vector
,但失败了。由于我无法看到运行时 Vector 中将包含哪种类型的对象,因此您可以首先使用 System.out.println(i.next().getClass().getCanonicalName()); 在当前错误发生的行之前。这会打印 Vector 元素的类型。
I doubt that the code works like this, methods such as
hasNext()
are missing the parentheses. If you copied the code, please do so again as having us guessing your code won't improve the quality of the answers.Your problem is that you want to access an element from the Vector. But The type of the objects inside the Vector is not
Vector
, but a different type of collection. You want to retrieve an element of this Vector (which is perfectly fine), but then you try to cast it toVector
, which fails.As I cannot see which type of objects will be in the Vector at runtime, you could, for a start, use
System.out.println(i.next().getClass().getCanonicalName());
before the line where your current error occurs. That prints the type of the Vector's element.嗯,更好的是直接在 JPA 查询中创建 DTO:
类似这样的东西(这不是经过验证的代码)
Hmm, better is to create DTO directly inside JPA query:
Something like this (this is not verified code)