94

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

chimeracoder
  • 20,648
  • 21
  • 60
  • 60

6 Answers6

205

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.

evandrix
  • 6,041
  • 4
  • 27
  • 38
dhm
  • 2,278
  • 1
  • 13
  • 6
33

If you ever need to do this dynamically, you can use the following:

boolean isInstance(Object object, Class<?> type) {
    return type.isInstance(object);
}

You can get an instance of java.lang.Class by calling the instance method Object::getClass on any object (returns the Class which that object is an instance of), or you can use class literals (for example, String.class, List.class, int[].class). There are other ways as well, through the reflection API (which Class itself is the entry point for).

gdejohn
  • 7,451
  • 1
  • 33
  • 49
  • or better yet, use IsAssignableFrom(Class) – Chii Nov 28 '10 at 06:05
  • 1
    @Chii But then you need to call `getClass` on `a` again, which is what thebackhand was trying to avoid. – gdejohn Nov 28 '10 at 09:13
  • no - all you need is references to the classes you want to compare - a.getClass().isAssignableFrom(MyClass.class) , or the other way around. – Chii Nov 29 '10 at 08:29
  • 1
    @Chii That's assuming he knows what class he wants to compare to ahead of time. My answer was for doing it dynamically. – gdejohn Nov 29 '10 at 11:36
  • Does this work for inherited objects as well ? Like if class ```Sub``` derives from ```Super``` and in a method, the signature is ```method(Super super)``` then if I evaluate ```super isinstanceof Sub```, will it work if an object of type ```Sub``` is passed as a parameter to this method ? – Aritro Shome Oct 07 '21 at 04:17
  • @AritroShome If I'm understanding your question correctly, then yes, that will work. You can test this easily with jshell. – gdejohn Oct 07 '21 at 16:40
  • @gdejohn Yeah, thanks. I guess in this era of IDEs, I tend to forget tools like ```jshell``` ! – Aritro Shome Oct 08 '21 at 05:18
21

Use the instanceof operator:

if(a instanceof MyClass)
{
    //do something
}
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
6

I agree with the use of instanceof already mentioned.

An additional benefit of using instanceof is that when used with a null reference instanceof of will return false, while a.getClass() would throw a NullPointerException.

Justin Muller
  • 1,283
  • 13
  • 21
5

Try operator instanceof.

Kos
  • 70,399
  • 25
  • 169
  • 233
3

The usual way would be:

if (a instanceof A)

However, there are cases when you can't do this, such as when A in a generic argument.

Due to Java's type erasure, the following won't compile:

<A> boolean someMethod(Object a) {
    if (a instanceof A)
    ...
}

and the following won't work (and will produce an unchecked cast warning):

<A> void someMethod(Object a) {
    try {
        A casted = (A)a;    
    } catch (ClassCastException e) {
         ...
    }
}

You can't cast to A at runtime, because at runtime, A is essentially Object.

The solutions to such cases is to use a Class instead of the generic argument:

void someMethod(Object a, Class<A> aClass) {
    if (aClass.isInstance(a)) {
       A casted = aClass.cast(a);
       ...
    }
}

You can then call the method as:

someMethod(myInstance, MyClass.class);
someMethod(myInstance, OtherClass.class);
Martin Konicek
  • 39,126
  • 20
  • 90
  • 98