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

StackOverflow https://stackoverflow.com/questions/16688655

  •  30-05-2022
  •  | 
  •  

Question

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)

Était-ce utile?

La solution

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.

Autres conseils

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));


    }

I have read all the answers which have been posted so far but couldn't find satisfactory answer yet. Answering to Is there some kind of statement like instanceof for this check? or I should use qux.getClass().equals(Foo.class) question I would say yes, there is instanceof operator in java to check if the object is instance of class. Below is an example-:

class Vehicle {

}

class Car extends Vehicle {

}

public class Research {
    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle();

        if (vehicle instanceof Vehicle) {
            System.out.println("vehicle instanceof Vehicle : TRUE");
        } else {
            System.out.println("vehicle instanceof Vehicle : FALSE");
        }

        if (vehicle instanceof Car) {
            System.out.println("vehicle instanceof Car : TRUE");
        } else {
            System.out.println("vehicle instanceof Car : FALSE");
        }

        System.out.println();
        Car car = new Car();

        if (car instanceof Vehicle) {
            System.out.println("car instanceof Vehicle : TRUE");
        } else {
            System.out.println("car instanceof Vehicle : FALSE");
        }

        if (car instanceof Car) {
            System.out.println("car instanceof Car : TRUE");
        } else {
            System.out.println("car instanceof Car : FALSE");
        }
    }
}

Output-:

vehicle instanceof Vehicle : TRUE
vehicle instanceof Car : FALSE

car instanceof Vehicle : TRUE
car instanceof Car : TRUE

Description-:instanceof operator tells if an object is a instance of a class or it's parent classes (up to any level).
vehicle instanceof Car : FALSE line of output is indicating that instanceof operator will not tell if an object is a instance of its sub class.

Another way is to use getClass().equals(Foo.class) to determine if an object is a instance of a class or not. Let us see below example-:

class Vehicle {

}

class Car extends Vehicle {

}

public class Research {
    public static void main(String[] args) {
        Vehicle vehicle = new Vehicle();

        if (vehicle.getClass().equals(Vehicle.class)) {
            System.out.println("vehicle instanceof Vehicle : TRUE");
        } else {
            System.out.println("vehicle instanceof Vehicle : FALSE");
        }

        if (vehicle.getClass().equals(Car.class)) {
            System.out.println("vehicle instanceof Car : TRUE");
        } else {
            System.out.println("vehicle instanceof Car : FALSE");
        }

        System.out.println();
        Car car = new Car();

        if (car.getClass().equals(Vehicle.class)) {
            System.out.println("car instanceof Vehicle : TRUE");
        } else {
            System.out.println("car instanceof Vehicle : FALSE");
        }

        if (car.getClass().equals(Car.class)) {
            System.out.println("car instanceof Car : TRUE");
        } else {
            System.out.println("car instanceof Car : FALSE");
        }


    }
}

Output-:

vehicle instanceof Vehicle : TRUE
vehicle instanceof Car : FALSE

car instanceof Vehicle : FALSE
car instanceof Car : TRUE

Description-: It would be clear from the above example that which one(out of above two) should be opted where?

Important Notes-:

  1. instanceof operator will not throw NullPointerException exception in case if reference variable is not pointing to any object(i.e. its having null reference).
  2. car.getClass().equals(Car.class) will throw NullPointerException exception in case if car is not pointing to any object(i.e. its having null reference). Therefore one must place extra null check with this for example car != null && car.getClass().equals(Car.class) to prevent it from NullPointerException.
  3. instanceof operator tells if an object is a instance of a class or it's parent classes (up to any level).
  4. car.getClass().equals(Car.class) will tell if an object is a instance of class only. (Parent & Sub classes will not be considered at all)
    package com.instance;

    public class Foo {
        public void instance(Foo f) {
            System.out.println("---------");
            System.out.println(f.getClass());
            System.out.println(getClass());
            if (f.getClass() == getClass()) {
                System.out.println("Yes");
            } else {
                System.out.println("No");
            }
        }
    }


package com.instance;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Foo f1 = new Foo();
        Foo f2 = new Foo();
        Foo f3 = new Bar();
        f1.instance(f1);
        f1.instance(f2);
        f1.instance(f3);
    }

}

Well you already know that qux is instanceof Foo (unless it's null...), so a simple qux instanceof Bar and a null check should be all you need.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top