简体   繁体   English

如何转换对象数组?

[英]how to cast object array?

I am new to java and exploring java ee application with netbeans. 我是Java的新手,正在使用netbeans探索Java ee应用程序。

I have the code : 我有代码:

Method in userbean: 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 我使用这种方法来构造jsf数据表,并与netbeans6.5和glassfish2一起正常工作

however when i use the same method except i change the vector to arraylist in netbean 6.9 但是,当我使用相同的方法时,除了将向量更改为netbean 6.9中的arraylist

and glassfish 3 i got the class cast 和glassfish 3我上了班

exception at run time: object cannot be cast to java.util.list; 运行时异常: 无法将对象强制转换为java.util.list;

Does anybody know how to do it? 有人知道怎么做吗? thank you.. 谢谢..

Hmm, better is to create DTO directly inside JPA query: 嗯,更好的方法是直接在JPA查询中创建DTO:

public List userList() {

  Query q = em.createNativeQuery("SELECT new UserState(username,address) FROM tbuser");

  return q.getResultList();

}

Something like this (this is not verified code) 这样的东西(这不是经过验证的代码)

I doubt that the code works like this, methods such as hasNext() are missing the parentheses. 我怀疑代码是否像这样工作,诸如hasNext()方法缺少括号。 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. 您的问题是您要访问Vector中的元素。 But The type of the objects inside the Vector is not Vector , but a different type of collection. 但是Vector内部对象的类型不是Vector ,而是集合的另一种类型。 You want to retrieve an element of this Vector (which is perfectly fine), but then you try to cast it to Vector , which fails. 您想检索此Vector的一个元素(这很好),但随后尝试将其强制转换为Vector ,这将失败。

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()); 由于我看不到运行时Vector中将包含哪种类型的对象,因此可以首先使用System.out.println(i.next().getClass().getCanonicalName()); before the line where your current error occurs. 当前错误发生的行之前。 That prints the type of the Vector's element. 打印出Vector元素的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM