Reputation: 3941
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.
Upvotes: 44
Views: 30012
Reputation: 1516
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
Upvotes: 57
Reputation: 467
Here is a simple explanation with a solution.
You have:
Object obj =t1
;
where t1
is an object of class T.
And you have other object T called t
.
T t = new T()
;
How to check if obj
is the same type of t
?
Solution:
if(obj is t)
print('obj is typeof t')
else print('obj is not typeof t')
Upvotes: 0
Reputation: 16263
By using the is
and is!
operators, like this:
if (someObject is T)
From the documentation:
The
is
andis!
operators are handy for checking types. The result ofobj is T
is true ifobj
implements the interface specified byT
. For example,obj is Object
is always true.
Using the Mirrors API (see this example):
Expect.equals('T', someObject.simpleName)
Upvotes: 56