instanceof和Class.isAssignableFrom(...)有什么区别? [英] What is the difference between instanceof and Class.isAssignableFrom(...)?

查看:122
本文介绍了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 ,你需要在编译时知道 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.

这篇关于instanceof和Class.isAssignableFrom(...)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆