instanceof和Class.isAssignableFrom(...)有什么区别?

问题描述:

以下哪项更好?

a instanceof B

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

我所知道的唯一区别是,当'a'为空时,第一个返回false,而第二个抛出异常。除此之外,他们总是给出相同的结果吗?

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?

当使用 instanceof $ c时$ c>,你需要在编译时知道 B 的类。当使用 isAssignableFrom()时,它可以是动态的并在运行时更改。

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.