Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof yields inconsistent results for detecting interfaces?

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.

like image 215
morgancodes Avatar asked Mar 10 '09 16:03

morgancodes


1 Answers

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.

like image 193
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet