Check if an object is an instance of a class (but not an instance of its subclass)

For this example:

public class Foo{}

public class Bar extends Foo{}

....

void myMethod(Foo qux){
   if (checkInstance(qux,Foo.class)){
     ....
   }
}

How can I check if qux is an instance of Foo (but not an instance of its subclass of foo)? That is:

  • checkInstance(qux,Foo.class)=true
  • checkInstance(qux,Bar.class)=false

Is there some kind of statement like instanceof for this check? or I should use qux.getClass().equals(Foo.class)


If you have to do this, the only way would be the getClass().equals(Foo.class) option you've suggested.

However, the goal of OO design is to allow you to treat any Foo in the same fashion. Whether or not the instance is a subclass should be irrelevant in a normal program.


If you are looking for exact class match the only means is qux.getClass().equals(Foo.class). instanceof will also return true for subclasses.


you should use instanceof

if(qux instanceof Foo && !(qux instanceof Bar)) {
    ...
}

This works with both classes and interfaces, so in most cases it should preferred over .class which does not work with interfaces.


I just tried following code, it seems like working fine

public class BaseClass {

    private String a;

    public boolean isInstanceOf(BaseClass base){
        if(base == null){
            return false;
        }
        else if(getClass() == base.getClass()){
            return true;
        }else{
            return false;
        }
    }

}



public class DervidClass extends BaseClass {


    public boolean isInstanceOf(DervidClass base) {
        if(base == null){
            return false;
        }
        else if(getClass() == base.getClass()){
            return true;
        }else{
            return false;
        }
    }


}

public class myTest {
public static void main(String[] args) throws ParseException {


        BaseClass base = new BaseClass();
        BaseClass base1 = new BaseClass();
        DervidClass derived = new DervidClass();

        BaseClass d1 = new DervidClass();

        System.out.println(base.isInstanceOf(d1));
        System.out.println(d1.isInstanceOf(d1));
        System.out.println((d1 instanceof BaseClass));


    }