Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if an object is an instance of a class

How can I determine whether an object is of a class or not in the Dart language?

I'm looking to do something like the following:

if (someObject.class.toString() == "Num") {     ... } 

And what is the returned value type? Will it have to be a String?


The mirror library has been up and down and seems to be subject to rapid change right now, as the one thing I did find simply did not work as shown.

like image 356
george koller Avatar asked Oct 14 '12 06:10

george koller


People also ask

What is an object an object is an instance of a class?

object: an object is an element (or instance) of a class; objects have the behaviors of their class. The object is the actual component of programs, while the class specifies how instances are created and how they behave. method: a method is an action which an object is able to perform.

Why object is an instance of a class?

A class can create objects of itself with different characteristics and common behaviour. So, we can say that an Object represents a specific state of the class. For these reasons, an Object is called an Instance of a Class.

How do I check if an object is an instance of a given class or of a subclass of it?

The isinstance() method checks whether an object is an instance of a class whereas issubclass() method asks whether one class is a subclass of another class (or other classes).

What is an instance of a class example?

Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle. Instantiation − The creation of an instance of a class.


1 Answers

Recently Object got the runtimeType getter. So now, we may not only compare type of object with another type, but actually get the class name of an object.

As in:

myObject.runtimeType.toString() 

Furthermore, in the current version of Dart, you can skip the toString operation and directly compare runtimeType of object with target type:

myObject.runtimeType == int 

or

myObject.runtimeType == Animal 
like image 166
Vadim Tsushko Avatar answered Sep 21 '22 19:09

Vadim Tsushko