So I had an interesting issue in my new project today.
Th cause of the bug is not that strange itself, what essentially happened was that a Hibernate mapping was missing in one of the project’s shared libraries. This caused the query that was suppose to return a collection of the domain objects to instead return a collection of map objects.
So far, totally understandable behavior. But it’s how I found out about this bug that was unusual.
Collection<Domain> objs = daoImpl.getDomains(); // was actually returning a collection of maps if (objs != null) { for (Domain d : objs) { //do something with d } }
This is roughly the code I had that used the share library. I had expected the InvalidCastException to be thrown at line 1. However it was not until line 3 when the for loop was executing before Java detected that something was wrong.
To be sure of this I even stepped the code through the debugger, yep, I can clearly see that it was a Collection of maps, and it is definitely not picked up until the for loop.
It was driving me crazy, I even entertained the thought that maybe java.util.Map secretly inherited my domain object somehow.
Then it suddenly hit me, Java generic type checking is enforced only at compile time. Since Hibernate is creating the domain objects by reflection, the compiler couldn’t possibly have known the class mismatch.
Lesson to remember, beware when pulling in new shared library.