Check if an object belongs to a class in Java

chimeracoder picture chimeracoder · Nov 28, 2010 · Viewed 153.8k times · Source

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"?

Answer

dhm picture dhm · Nov 28, 2010

The instanceof keyword, as described by the other answers, is usually what you would want. Keep in mind that instanceof will return true for 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 via ClassName.class.

So for example:

if (a.getClass() == X.class) {
  // do something
}

In the above example, the condition is true if a is an instance of X, but not if a is an instance of a subclass of X.

In comparison:

if (a instanceof X) {
    // do something
  }

In the instanceof example, the condition is true if a is an instance of X, or if a is an instance of a subclass of X.

Most of the time, instanceof is right.