加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 是什么意思isInstance是instanceof的“动态等价物”?

发布时间:2020-12-15 03:15:20 所属栏目:Java 来源:网络整理
导读:什么意思’动态等价’? 我只是想知道具有this.getClass().isInstance(aClass)而不是这个aClass实例的目的是什么?有区别吗? Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the
什么意思’动态等价’?

我只是想知道具有this.getClass().isInstance(aClass)而不是这个aClass实例的目的是什么?有区别吗?

Determines if the specified Object is assignment-compatible with the
object represented by this Class. This method is the dynamic
equivalent of the Java language instanceof operator

解决方法

是.不仅顺序不一样,而且Clazz的对象实例必须有一个在编译时已知的类. clazz.isInstance(object)可以使用运行时已知的类.

还有一个微妙的区别是isInstance会自动装箱,但是instanceof不会.

例如

10 instanceof Integer // does not compile
Integer.class.isInstance(10) // returns true

Integer i = 10;
if (i instanceof String) // does NOT compile
if (String.class.isInstance(i)) // is false

为了看到差异,我建议你尝试使用它们.

注意:如果你执行object.getClass().getClass()或myClass.getClass(),你将获得一个Class注意不要在不需要时调用getClass().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读