Java instanceof and byte[]
It looks like you have a !
(not) that you don't need
if (!(potentialByteArray instanceof byte[])) {...}
should be
if (potentialByteArray instanceof byte[]) {...}
Joseph Weissman
Hi! I'm Joseph. I am a computer programmer (my Github) and thinker/writer (my working group's blog.) I'm one of the friendly neighborhood moderators at Philosophy StackExchange.
Updated on June 09, 2022Comments
-
Joseph Weissman almost 2 years
What I would expect is that '
potentialByteArray instanceof byte[]
would return true whenpotentialByteArray
is an instance of abyte[]
, but this doesn't seem to happen -- it's always false for some reason!I've got a conditional that looks like the following:
if (!(potentialByteArray instanceof byte[])) { /* ... process ... */ } else { log.warn("--- can only encode 'byte[]' message data (got {})", msg.getClass().getSimpleName()); /* ... handle error gracefully ... */ }
...and what this outputs is the following:
--- can only encode 'byte[]' message data (got byte[])
Which means that the object actually was a
byte[]
but wasn't aninstanceof byte[]
somehow. So... would this work forByte[]
instead or something? What's really going on here, and why isn't this working as I am expecting?What's an appropriate idiom to use here instead?