Wednesday, July 02, 2008

Interesting Java behavior

I recently was working with a generic list that was being populated by Hibernate.


List fooList = getFooFromHibernate();
for (Foo foo : fooList)
{
// do stuff
}

I was getting ClassCastExceptions while iterating through the list. It took a while to figure out, but the getFooFromHibernate method had a join to the BAR table in it without selecting the fields. Because of this Hibernate dumped a Foo into the list AND a Bar. When I iterated through the list, I got the exception.

This behavior can be caught with integration tests by iterating through the lists retrieved from the database.

2 Comments:

Blogger JessiTRON said...

sounds like interesting Hibernate behaviour. Is it Java's fault?

Why doesn't it use generics?

5:03 PM  
Blogger mypetrock said...

The problem is that the generics are checked at compile time, not at run time. Since Hibernate is loading untyped objects into a list at run-time, there isn't the type safety that you would expect.

1:57 PM  

Post a Comment

<< Home