instanceof 和 Class.isAssignableFrom(...) 有什么区别?
问题描述:
以下哪个更好?
a instanceof B
或
B.class.isAssignableFrom(a.getClass())
我所知道的唯一区别是,当 'a' 为 null 时,第一个返回 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
时,编译时需要知道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.