Search code examples
javaclassmethodsinstanceof

Using instanceof with a class Object


What's the correct syntax to make this work?

public boolean isTypeOf(Class type) {
     return this instanceof type;
}

I intend to call it with:

foo.isTypeOf(MyClass.class);

The method will be overriden, otherwise I would just use instanceof inplace.


Solution

  • Use Class.isInstance(obj):

    public boolean isTypeOf(Class type) {
         return type.isInstance(this);
    }
    

    This method determines if the given parameter is an instance of the class. This method will also work if the object is a sub-class of the class.

    Quoting from the Javadoc:

    This method is the dynamic equivalent of the Java language instanceof operator.