天天看點

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

I think the official

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 <code>isInstance()</code> 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:

In general, I‘d say that using <code>instanceof</code> 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

<code>isInstance()</code> instead.

For <code>instanceof</code> you need to know the exact class at compile

time.

For <code>isInstance</code> the class is decided at run time. (late

binding) e.g.