The simpler and faster code is:
if (myObject instanceof B) {
} else if (myObject instanceof C) {
} else if (myObject instanceof A) {
}
Note that the order is important: you have to have the test for A
last, as that will succeed for instances of B
and C
as well.
However, your original code would nearly work. Class.isInstance
checks whether the value really is an instance of the given class or any superclass. So if myObject
is an instance of C
, then B.class.isInstance(myObject)
will return false. All you've got wrong is that you're calling getClass()
on myObject
unnecessarily, instead of using B.class
etc.
This is the approach you would take if you didn't know which classes you were interested in at compile time - the instanceof
operator only works when you can specify the type statically in code.
Now if you want to find out whether myObject
is an instance of exactly B
(and not a subclass) then just use:
if (myObject.getClass() == B.class)
(This will blow up if myObject
is a null reference, of course.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…