Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 520
Addev Avatar asked May 22 '13 09:05

Addev


People also ask

How can we check whether the object is instance of class or not?

Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .

How do you know if something is a subclass?

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.

Does Isinstance work on subclasses?

In other words, isinstance is true for subclasses, too.

Can an object be an instance of a class?

An instance of a class is an object. It is also known as a class object or class instance. As such, instantiation may be referred to as construction. Whenever values vary from one object to another, they are called instance variables.


1 Answers

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.

like image 194
Duncan Jones Avatar answered Oct 25 '22 17:10

Duncan Jones