jpa - java.lang.String cannot be cast to [Ljava.lang.String; -


i have following , error

java.lang.string cannot cast [ljava.lang.string;

i have changed object[] string[] because faced next error:

java.lang.object cannot cast [ljava.lang.string;

any idea?

private collection querystatement(string selectstatement) {      int colcount = 0;     int rowcount = 0;     int rowcounter = 0;      arraylist = new arraylist();      query query = getentitymanager().createnativequery(selectstatement);      list<string[]> resultlist = (list<string[]>) query.getresultlist();      if (!resultlist.equals(collections.emptylist())) {         rowcount = resultlist.size();     }      if (rowcount > 0) {         colcount = ((string[]) query.getresultlist().get(0)).length;     }      rows = rowcount;     cols = colcount;      string[][] array = new string[rowcount][colcount];      (string[] obj : resultlist) {         string[] record = new string[colcount];         (int colcounter = 0; colcounter < colcount; colcounter++) {             record[colcounter] = safevalue(obj[colcounter]+"");         }          array[ rowcounter++] = (string[]) record;     }     a.add(array);     return a; } 

java.lang.string cannot cast [ljava.lang.string;

this error occurs when try cast string array of string.

for example:

list list = new arraylist<>(); list.add("foo"); string[] values = (string[])list.get(0); -> throws exception 

for me error because query.getresultlist() returns list<string> or list<object> instead of list<string[]> such when try cast value string[] exception.


according javadoc createnativequery(string) returns result of type object[] or result of type object if there 1 column in select list.

approach #1

one simple way fix it, rely on raw type result (it not elegant approach simplest one) later can check type of content of list cast properly.

list result = query.getresultlist(); 

then check type can proceed next:

if (resultlist.isempty() || resultlist.get(0) instanceof object[]) {     // several columns in result     list<object[]> resultlist = (list<object[]>) result;     // rest of current code here } else {     // 1 column in result     list<object> resultlist = (list<object>) result;     ... } 

approach #2

a more elegant way create pojo , use createnativequery(string sqlstring, class resultclass) create query, way automatically map columns fields of pojo

here how like

private collection<t> querystatement(string selectstatement, class<t> resulttype) {     ...     query query = getentitymanager().createnativequery(selectstatement, resulttype);     list<t> resultlist = (list<t>) query.getresultlist();     ... } 

Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -