0

I am getting java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to ...model.MyClassAttributes exception at for(MyClassAttributes mc : atList) , even if I have done a cast to the entity.

List<MyClassAttributes> atList = new ArrayList<MyClassAttributes>();
atList=(List<MyClassAttributes>)session.createSQLQuery(SELECT_QR_SQL).setLong("rec", rec).list();
for(MyClassAttributes mc : atList)
{

}

When I checked the compiled class it seems cast didnt update.

atList = session.createSQLQuery("Select col from....").setLong("rec", rec.longValue()).list();

What is the issue here?

5
  • What does session.createSQLQuery return? Commented Nov 17, 2015 at 17:49
  • select col1,col2 from some_table where col3=:some_val - returns object list Commented Nov 17, 2015 at 17:53
  • Try casting it to a normal List without generics. It just returns a simple list. Click here Commented Nov 17, 2015 at 17:54
  • What's the point of assigning a new ArrayList if you immediately replace it by the result of the other call? Commented Nov 17, 2015 at 18:00
  • Yeah, that's redundant, but shouldn't be part of the actual problem. But of course, that initialization of the local variable should be removed for being pointless. Commented Nov 17, 2015 at 18:30

2 Answers 2

0

Java does not know any generics at runtime. This is called "type erasure". Since the list() method already returns a List<A>, typecasting it to some other List<B> (where B is a subclass of A) doesn't generate any additional bytecode.

Note how the ClassCastException occurs in the for loop, not the assignment. With the loop variable you (and also the compiler, since you casted before) assume that the List contains only null and MyClassAttributes objects, but apparently that isn't the case, since the exception is thrown.

-1

Can you try this? Don't initialize the List object. Just declare it eg -

List<MyClassAttributes> atList;

The reason the cast isn't working is - You have a List instance with an ArrayList Object in it. And the sqlQuery<>.list() function is returning a List.

Casts work only when the 'is-a' relationship is satisfied.

ArrayList is-a(always) List. So you can cast an ArrayList instance as a List. But the List may not be an ArrayList all the time. So the cast doesn't work.

1
  • Actually, it doesn't matter what was assigned to the atList variable before assigning something else. Particularly the value of a variable doesn't affect any unrelated typecasting. The ClassCastException really tells that the list doesn't contain MyClassAttributes objects, at least not exclusively. Commented Nov 17, 2015 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.