This is most likely because hibernate is returning a proxy.
Why does it do this? To implement lazy loading the framework needs to intercept your method calls that return a lazy loaded object or list of objects. It does this so it can first load the object from the DB and then allow your method to run. Hibernate does this by creating a proxy class. If you check the type in debug you should be able to see the actual type is a generated class which does not extend from your base class.
How to get around it? I had this problem once and successfully used the visitor pattern instead of using instanceof
. It does add extra complication so it's not everyone's favorite pattern but IMHO it is a much cleaner approach than using instanceof
.
If you use instanceof
then you typically end up with if...else
blocks checking for the different types. As you add more types you will have to re-visit each of these blocks. The advantage of the visitor pattern is that the conditional logic is built into your class hierarchy so if you add more types it makes it less likely you need to change everywhere that uses these classes.
I found this article useful when implementing the visitor pattern.