instanceof yields inconsistent results for detecting interfaces?

morgancodes picture morgancodes · Mar 10, 2009 · Viewed 7.9k times · Source

Is there anything tricky I should know about instanceof? I'm passing a list of objects through a few methods and testing whether these objects implement a particular interface using instanceof. In some cases, instanceof correctly identifies objects as implementing the interface, in other cases it doesn't. It appears to be giving me inconsistent results on the same object in different places. Is there any trick/gotcha I should be aware of here?

In anticipation of comments you might have:

1) I know instanceof is bad form. I'm working with a less-than-perfect object hierarchy that can't be changed, and this is the least bad thing I can think to do.

2) I'm working to create a code example, but I'll need to simplify my code a lot if I'm going to paste in anything useful here. In the meantime, if you've seen this before and can shed some light, please do.

Answer

Jon Skeet picture Jon Skeet · Mar 10, 2009

Are you loading any types dynamically, potentially from different classloaders? The only time I've seen apparently inconsistent results was when I had two lines of code which look like they refer to the same type, but which have actually loaded that type from different classloaders.