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

独自空忆成欢 提交于 2019-11-27 13:26:35

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


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

}

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)

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!