What is the difference between instanceof and Class.isAssignableFrom(...)?

Megamug picture Megamug · Jan 30, 2009 · Viewed 261.6k times · Source

Which of the following is better?

a instanceof B

or

B.class.isAssignableFrom(a.getClass())

The only difference that I know of is, when 'a' is null, the first returns false, while the second throws an exception. Other than that, do they always give the same result?

Answer

Marc Novakowski picture Marc Novakowski · Jan 30, 2009

When using instanceof, you need to know the class of B at compile time. When using isAssignableFrom() it can be dynamic and change during runtime.