Type introspection
Encyclopedia
In computing
Computing
Computing is usually defined as the activity of using and improving computer hardware and software. It is the computer-specific part of information technology...

, type introspection is a capability of some object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

 language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

s to determine the type of an object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...

 at runtime. This is a notable capability of the Objective-C
Objective-C
Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...

 language, and is a common feature in any language that allows object classes to be manipulated as first-class object
First-class object
In programming language design, a first-class citizen , in the context of a particular programming language, is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable...

s by the programmer. Type introspection can be used to implement polymorphism.

Ruby

Type introspection is a core feature of Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

. 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
Interactive Ruby Shell
Interactive Ruby Shell is a shell for programming in the object-oriented scripting language Ruby. The program is launched from a command line and allows the execution of Ruby commands with immediate response, experimenting in real-time...

):

$ irb
irb(main):001:0> A=Class.new> true

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. The example below shows an alternative method in Ruby that can be used to define classes (and leads to the same result):

$ irb
irb(main):001:0> class A; end> true

Or you can directly ask for the class of any object, and "compare" them (code below assumes having executed the code above):

irb(main):008:0> A.instance_of? Class

Objective-C

In Objective-C
Objective-C
Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...

, for example, both the generic Object and NSObject (in Cocoa
Cocoa (API)
Cocoa is Apple's native object-oriented application programming interface for the Mac OS X operating system and—along with the Cocoa Touch extension for gesture recognition and animation—for applications for the iOS operating system, used on Apple devices such as the iPhone, the iPod Touch, and...

/OpenStep
OpenStep
OpenStep was an object-oriented application programming interface specification for an object-oriented operating system that used a non-NeXTSTEP operating system as its core, principally developed by NeXT with Sun Microsystems. OPENSTEP was a specific implementation of the OpenStep API developed...

) provide the method
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...

 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

- desex: (id) to_desex
{
if([to_desex isKindOfClass:[Animal class]])
{
//we're actually desexing an Animal, so continue
if([to_desex isMemberOfClass:[Puppy class]])
desex_dog(to_desex);
else if([to_desex isMemberOfClass:[Kitten class]])
desex_cat(to_desex);
else
error;
}
else
{
error;
}
}


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
Typeid
In C++, the typeid keyword is used to determine the class of an object at run time. It returns a reference to std::type_info object, which exists until the end of the program...

 and dynamic cast
Dynamic cast
In the C++ programming language, the dynamic_cast operator is a part of the run-time type information system that performs a typecast. Unlike an ordinary C-style typecast, a type safety check is performed at runtime, and if the types are not compatible, an exception will be thrown or a null...

 keywords.
The dynamic_cast expression can be used to determine whether a particular object is of a particular derived class. For instance:

if (Person *p = dynamic_cast(obj)) {
p->walk;
}

The typeid operator retrieves a std::type_info object describing the most derived type of an object:

if (typeid(Person) typeid(*obj)) {
serialize_person( obj );
}

Object Pascal

Type introspection has been a part of Object Pascal since the original release of Delphi, which uses RTTI heavily for visual form design. In Object Pascal, all classes descend from the base TObject class, which implements basic RTTI functionality. Every class's name can be referenced in code for RTTI purposes; the class name identifier is implemented as a pointer to the class's metadata, which can be declared and used as a variable of type TClass.
The language includes an is operator, to determine if an object is or descends from a given class, an as operator, providing a type-checked typecast, and several TObject methods.

procedure Form1.MyButtonOnClick(Sender: TObject);
var
aButton: TButton;
SenderClass: TClass;
begin
SenderClass := Sender.ClassType; //returns Sender's class pointer
if sender is TButton then
begin
aButton := sender as TButton;
EditBox.Text := aButton.Caption; //Property that the button has but generic objects don't
end
else begin
EditBox.Text := Sender.ClassName; //returns the name of Sender's class as a string
end;
end;

Java Object Introspection

The simplest example of type introspection in Java is the instanceof operator. The instanceof operator determines whether a particular object belongs to a particular class (or a subclass of that class, or a class that implements that interface). For instance:

if(obj instanceof Person){
Person p = (Person)obj;
p.walk;
}


The java.lang.Class class is the basis of more advanced introspection.

For instance, if it is desirable to determine the actual class of an object (rather than whether it is a member of a particular class), Object.getClass and Class.getName can be used:


System.out.println(obj.getClass.getName);

PHP

In PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

 introspection can be done using instanceof operator. For instance:

if ($obj instanceof Person) {
// Do whatever you want
}

Perl

Introspection can be achieved using the ref and isa functions in Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

.

We can introspect the following classes and their corresponding instances:

package Animal;
sub new {
my $class = shift;
return bless {}, $class;
}

package Dog;
use base 'Animal';

package main;
my $animal = Animal->new;
my $dog = Dog->new;

using:

print "This is an Animal.\n" if ref $animal eq 'Animal';
print "Dog is an Animal.\n" if $dog->isa('Animal');

Meta-Object Protocol

Much more powerful introspection in Perl can be achieved using the Moose
Moose (Perl)
Moose is an extension of the Perl 5 object system. It brings modern object-oriented language features to Perl 5, making object-oriented programming more consistent and less tedious.-Features:...

 object system and the Class::MOP meta-object protocol, for example this is how you can check if a given object does a role X:


if ($object->meta->does_role("X")) {
# do something ...
}


This is how you can list fully qualified names of all of the methods that can be invoked on the object, together with the classes in which they were defined:


for my $method ($object->meta->get_all_methods) {
print $method->fully_qualified_name, "\n";
}

Python

The most common method of introspection in Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

 is using the dir function to detail the attributes of an object. For example:

class foo(object):
def __init__(self, val):
self.x = val
def bar(self):
return self.x

...

>>> dir(foo(5))
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'bar', 'x']


Also, the built-in functions isinstance and hasattr can be used to determine what an object is and what an object does respectively. For example:

>>> a = foo(10)
>>> isinstance(a, foo)
True
>>> hasattr(a, 'bar')
True

Actionscript (as3)

In Actionscript
ActionScript
ActionScript is an object-oriented language originally developed by Macromedia Inc. . It is a dialect of ECMAScript , and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of...

 the function flash.utils.getQualifiedClassName can be used to retrieve the Class/Type name of an arbitrary Object.

// all classes used in as3 must be imported explicitly
import flash.utils.getQualifiedClassName;
import flash.display.Sprite;
// trace is like System.print.out in Java or echo in PHP
trace(flash.utils.getQualifiedClassName("I'm am a String")); // "String"
trace(flash.utils.getQualifiedClassName(1)); // "int", see dynamic casting for why not Number
trace(flash.utils.getQualifiedClassName(new flash.display.Sprite)); // "flash.display.Sprite"


Or alternatively in actionscipt the operator is can be used to determine if an object is of a specific type

// trace is like System.print.out in Java or echo in PHP
trace("I'm a String" is String); // true
trace(1 is String); // false
trace("I'm am a String" is Number); // false
trace(1 is Number); // true


This second function can be used to test class inheritance
Inheritance (object-oriented programming)
In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...

 parents as well

import flash.display.DisplayObject;
import flash.display.Sprite; // extends DisplayObject

trace(new flash.display.Sprite is flash.display.Sprite); // true
trace(new flash.display.Sprite is flash.display.DisplayObject); // true, because Sprite extends DsiplayObject
trace(new flash.display.Sprite is String); // false

Meta-Type introspection

Like perl, actionscript can go further than getting the Class Name, but all the metadata, functions and other elements that make up an object using the flash.utils.describeType function, this is used when implementing reflection
Reflection (computer science)
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior at runtime....

 in actionscript.

import flash.utils.describeType;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flash.display.Sprite;

var className:String = getQualifiedClassName(new flash.display.Sprite); // "flash.display.Sprite"
var classRef:Class = getDefinitionByName(className); // Class reference to flash.display.Sprite
// eg. 'new classRef' same as 'new flash.display.Sprite'
trace(describeType(classRef)); // return XML object describing type
// same as : trace(describeType(flash.display.Sprite));

External links
  • Introspection on Rosetta Code
    Rosetta Code
    Rosetta Code is a wiki-based programming chrestomathy website with solutions to various programming problems in many different programming languages. It was created in 2007 by Mike Mol. Rosetta Code includes 450 programming tasks, and covers 351 programming languages...

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK