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

JavaInstanceof

Java Problem Overview


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)

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Solution 3 - Java

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.

Solution 4 - Java

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

Solution 5 - Java

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)

Solution 6 - Java

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

}


    

Solution 7 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAddevView Question on Stackoverflow
Solution 1 - JavaDuncan JonesView Answer on Stackoverflow
Solution 2 - Javanitegazer2003View Answer on Stackoverflow
Solution 3 - JavaMarco ForbergView Answer on Stackoverflow
Solution 4 - JavaKarthik PrasadView Answer on Stackoverflow
Solution 5 - JavaAshish KumarView Answer on Stackoverflow
Solution 6 - JavaboiledwaterView Answer on Stackoverflow
Solution 7 - JavavikingsteveView Answer on Stackoverflow