首页 > 其他 > 详细

When to use Class.isInstance() & when to use instanceof operator?

时间:2014-05-14 03:31:37      阅读:452      评论:0      收藏:0      [点我收藏+]

I think the official documentation gives you the answer to this one (albeit in a fairly nonspecific way):

This method is the dynamic equivalent of the Java language instanceof operator.

I take that to mean that isInstance() is primarily intended for use in code dealing with type reflection at runtime. In particular, I would say that it exists to handle cases where you might not know in advance the type(s) of class(es) that you want to check for membership of in advance (rare though those cases probably are).

For instance, you can use it to write a method that checks to see if two arbitrarily typed objects are assignment-compatible, like:

publicboolean areObjectsAssignable(Object left,Object right){return left.getClass().isInstance(right);}

In general, I‘d say that using instanceof should be preferred whenever you know the kind of class you want to check against in advance. In those very rare cases where you do not, use isInstance() instead.

 

For instanceof you need to know the exact class at compile time.

if(foo instanceofThisClassIKnowRightNow)...

For isInstance the class is decided at run time. (late binding) e.g.

if(someObject.getClass().isInstance(foo))...

When to use Class.isInstance() & when to use instanceof operator?,布布扣,bubuko.com

When to use Class.isInstance() & when to use instanceof operator?

原文:http://www.cnblogs.com/savagemorgan/p/3721940.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!