- Type introspection
In
computing , type introspection is a capability of someobject-oriented programming languages to determine the type of an object atruntime . This is a notable capability of theObjective-C language, and is a common feature in any language that allows object classes to be manipulated asfirst-class object s by the programmer. Type introspection can be used to implement polymorphism.Examples
Ruby
Type introspection is a core feature of Ruby as well. In Ruby, the Object class (ancestor of every class) provides Object#instance_of? and Object#kind_of? methods for checking the instance's class. The latter returns true when the particular instance the message was sent to is an instance of a descendant of the class in question. To clarify, consider the following example code (you can immediately try this with irb):In the example above, the Class class is used as any other class in Ruby. Two classes are created, A and B, the former is being a superclass of the latter, then one instance of each class is checked. The last expression gives true because A is a superclass of the class of b. In the example below the
syntactic sugar provided by Ruby is used to define classes (and leads to the same result):Or you can directly ask for the class of any object, and "compare" them (code below assumes having executed the code above):Objective-C
In
Objective-C , for example, both the generic Object and NSObject (inCocoa /OpenStep ) provide the method isMemberOfClass: which returns true if the argument to the method is an instance of the specified class. The method isKindOfClass: analogously returns true if the argument inherits from the specified class.For example, say we have a Puppy and Kitten class inheriting from Animal, and a Vet class.
Now, in the desex method we can write
Now, when desex is called with a generic object (an id), the function will behave correctly depending on the type of the generic object.
C++
C++ supports type introspection via the typeid operator. To enable this operator, the code must be compiled with
RTTI .Andrei Alexandrescu showed how to wrap the typeid operator in a Equality Comparable and LessThan Comparable class in his book Modern C++ programming. Code is available in the Loki library.
http://www.aoc.nrao.edu/~tjuerges/ALMA/ACS/Docs/ACS_docs/cpp/lokiTypeInfo_8h-source.html
http://www.sgi.com/tech/stl/LessThanComparable.html
http://www.sgi.com/tech/stl/EqualityComparable.html
ee also
*
Reflection (computer science)
*Introspector (program)
Wikimedia Foundation. 2010.