Is there an easy way to verify that an object belongs to a given class? For example, I could do
if(a.getClass() = (new MyClass()).getClass())
{
//do something
}
but this requires instantiating a new object on the fly each time, only to discard it. Is there a better way to check that “a” belongs to the class “MyClass”?
The
instanceofkeyword, as described by the other answers, is usually what you would want.Keep in mind that
instanceofwill returntruefor superclasses as well.If you want to see if an object is a direct instance of a class, you could compare the class. You can get the class object of an instance via
getClass(). And you can statically access a specific class viaClassName.class.So for example:
In the above example, the condition is true if
ais an instance ofX, but not ifais an instance of a subclass ofX.In comparison:
In the
instanceofexample, the condition is true ifais an instance ofX, or ifais an instance of a subclass ofX.Most of the time,
instanceofis right.