Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[Ljava.lang.Object; cannot be cast to error

Tags:

java

hibernate

I get a list from my query.list(). After that, I want to display the object inside this list but I got this error for this line for(Commerce[] c: this.newsList) {

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lcom.model.Commerce; com.action.CommerceAction.searchCommerces(CommerceAction.java:35)

Here is my code:

My business service

public List<Commerce[]> getCommercesBySearch(String categorie, String lieux) {
    Query query = hibUtil.getSession().createQuery("from Commerce c, Categorie ca,Lieux l "
            + "where c.categorie=ca.idCategorie and c.lieux=l.idLieux and"
            + " ca.libelle='" + categorie + "' and l.ville='" + lieux + "' ");
    List<Commerce[]> tuples = (List<Commerce[]>) query.list();
    return tuples;
}

My action class

private CommerceService service;
private Commerce commerce = new Commerce();
private List<Commerce[]> newsList;
public String searchCommerces() {
    String libelle = ServletActionContext.getRequest().getParameter("libelle");
    String ville = ServletActionContext.getRequest().getParameter("ville");
    this.newsList = service.getCommercesBySearch(libelle,ville);
    for(Commerce[] c: this.newsList){
        System.out.println(c[0].getNom());
    }
    if (this.newsList.size() > 0) {
        return SUCCESS;
    }
    addActionError("Il n'existe aucun commerce de cette catégorie dans cette ville");   
    return ERROR;
    }
like image 452
Nadk Avatar asked Dec 19 '22 05:12

Nadk


1 Answers

I am certain that this statement:

List<Commerce[]> tuples = (List<Commerce[]>) query.list();

produces an unchecked type conversion warning. Your code is polluting the heap by doing this unchecked type conversion. query.list() returns a raw List, which will contain Object[]. Here is the relevant Hibernate documentation:

Return the query results as a List. If the query contains multiple results per row, the results are returned in an instance of Object[].

Note that you cannot cast an array to an array of it's sub-type.

There are a couple of ways to fix this problem:

  1. Use List<Object[]> instead of List<Commerce[]>. You can then transform the result of the list() method into a more usable form, preferably within it's own method, before passing it on to the rest of your code. This is the preferable method if you need to select more than just the Commerce object.
  2. Add SELECT c to the beginning of your query, this will allow you to do a safe List<Commerce> cast.
like image 187
durron597 Avatar answered Dec 21 '22 23:12

durron597