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

Java

Java Problem Overview


> Possible Duplicate:
> Java isInstance vs instanceOf operator

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

Java is providing two option for checking assignment compatibility. Which to use when?

Java Solutions


Solution 1 - Java

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

if (foo instanceof ThisClassIKnowRightNow)
   ...

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

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

Solution 2 - Java

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:

public boolean 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJyotirupView Question on Stackoverflow
Solution 1 - Javauser949300View Answer on Stackoverflow
Solution 2 - JavaarothView Answer on Stackoverflow