HOME

TheInfoList



OR:

In
computing Computing is any goal-oriented activity requiring, benefiting from, or creating computing machinery. It includes the study and experimentation of algorithmic processes, and development of both hardware and software. Computing has scientific, e ...
, type introspection is the ability of a program to ''examine'' the type or properties of an
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ai ...
at runtime. Some
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
s possess this capability. Introspection should not be confused with
reflection Reflection or reflexion may refer to: Science and technology * Reflection (physics), a common wave phenomenon ** Specular reflection, reflection from a smooth surface *** Mirror image, a reflection in a mirror or in water ** Signal reflection, in s ...
, which goes a step further and is the ability for a program to ''manipulate'' the values, metadata, properties, and functions of an object at runtime. Some programming languages also possess that capability (e.g.,
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
,
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
,
Julia Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e.g. ...
, and Go).


Examples


Ruby

Type introspection is a core feature of
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
. In Ruby, the Object class (ancestor of every class) provides and 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. For example, consider the following example code (you can immediately try this with the
Interactive Ruby Shell Ruby is an interpreted, high-level, general-purpose programming language which supports multiple programming paradigms. It was designed with an emphasis on programming productivity and simplicity. In Ruby, everything is an object, including pr ...
): $ irb irb(main):001:0> A=Class.new => A irb(main):002:0> B=Class.new A => B irb(main):003:0> a=A.new => # irb(main):004:0> b=B.new => # irb(main):005:0> a.instance_of? A => true irb(main):006:0> b.instance_of? A => false irb(main):007:0> b.kind_of? A => true In the example above, the class is used as any other class in Ruby. Two classes are created, and , the former is being a superclass of the latter, then one instance of each class is checked. The last expression gives true because is a superclass of the class of . Further, 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 => true irb(main):009:0> a.class => A irb(main):010:0> a.class.class => Class irb(main):011:0> A > B => true irb(main):012:0> B <= A => true


Objective-C

In
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
, for example, both the generic Object and NSObject (in
Cocoa Cocoa may refer to: Chocolate * Chocolate * ''Theobroma cacao'', the cocoa tree * Cocoa bean, seed of ''Theobroma cacao'' * Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter and ...
/
OpenStep OpenStep is a defunct object-oriented application programming interface (API) specification for a legacy object-oriented operating system, with the basic goal of offering a NeXTSTEP-like environment on non-NeXTSTEP operating systems. OpenStep was ...
) provide the
method Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
which returns true if the argument to the method is an instance of the specified class. The method analogously returns true if the argument inherits from the specified class. For example, say we have an and an class inheriting from . Now, in the method we can write - (void)eat:(id)sth Now, when is called with a generic object (an ), the function will behave correctly depending on the type of the generic object.


C++

C++ supports type introspection via the
run-time type information In computer programming, run-time type information or run-time type identification (RTTI) is a feature of some programming languages (such as C++, Object Pascal, and Ada) that exposes information about an object's data type at runtime. Run-time typ ...
(RTTI)
typeid In computer programming, run-time type information or run-time type identification (RTTI) is a feature of some programming languages (such as C++, Object Pascal, and Ada) that exposes information about an object's data type at runtime. Run-time typ ...
and
dynamic_cast In computer programming, run-time type information or run-time type identification (RTTI) is a feature of some programming languages (such as C++, Object Pascal, and Ada) that exposes information about an object's data type at runtime. Run-time typ ...
keywords. The expression can be used to determine whether a particular object is of a particular derived class. For instance: Person* p = dynamic_cast(obj); if (p != nullptr) The operator retrieves a object describing the most derived type of an object: if (typeid(Person)

typeid(*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. Deeper introspection (enumerating fields and methods) is traditionally only supported for objects declared in the $M+ (a pragma) state, typically TPersistent, and only for symbols defined in the published section. Delphi 2010 increased this to nearly all symbols. 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

The simplest example of type introspection in Java is the operator. The 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) The 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), and can be used: System.out.println(obj.getClass().getName());


PHP

In
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group ...
introspection can be done using operator. For instance: if ($obj instanceof Person)


Perl

Introspection can be achieved using the and functions in
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
. We can introspect the following classes and their corresponding instances: package Animal; sub new 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 The moose (in North America) or elk (in Eurasia) (''Alces alces'') is a member of the New World deer subfamily and is the only species in the genus ''Alces''. It is the largest and heaviest extant species in the deer family. Most adult mal ...
object system and the
meta-object In computer science, a metaobject is an object that manipulates, creates, describes, or implements objects (including itself). The object that the metaobject pertains to is called the base object. Some information that a metaobject might define incl ...
protocol;Class::MOP - a meta-object protocol for Perl
/ref> for example, you can check if a given object ''does'' a
role A role (also rôle or social role) is a set of connected behaviors, rights, moral obligation, obligations, beliefs, and social norm, norms as conceptualized by people in a social situation. It is an expected or free or continuously changing behavi ...
: if ($object->meta->does_role("X")) 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)


Python

The most common method of introspection in
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
is using the function to detail the attributes of an object. For example: class Foo: 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 and can be used to determine what an object ''is'' while can determine what an object ''does''. For example: >>> a = Foo(10) >>> b = Bar(11) >>> type(a) >>> isinstance(a, Foo) True >>> isinstance(a, type(a)) True >>> isinstance(a, type(b)) False >>> hasattr(a, 'bar') True


ActionScript (as3)

In
ActionScript ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (meaning i ...
, the function flash.utils.getQualifiedClassName
/code> 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.out.println in Java or echo in PHP trace(flash.utils.getQualifiedClassName("I'm 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" Alternatively, the operator
/code> can be used to determine if an object is of a specific type: // trace is like System.out.println in Java or echo in PHP trace("I'm a String" is String); // true trace(1 is String); // false trace("I'm a String" is Number); // false trace(1 is Number); // true This second function can be used to test
class inheritance In object-oriented programming, inheritance is the mechanism of basing an Object (computer science), object or Class (computer programming), class upon another object (Prototype-based programming, prototype-based inheritance) or class (Class-based ...
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 DisplayObject 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
/code> function; this is used when implementing
reflection Reflection or reflexion may refer to: Science and technology * Reflection (physics), a common wave phenomenon ** Specular reflection, reflection from a smooth surface *** Mirror image, a reflection in a mirror or in water ** Signal reflection, in s ...
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.displaySprite // eg. 'new classRef()' same as 'new flash.display.Sprite()' trace(describeType(classRef)); // return XML object describing type // same as : trace(describeType(flash.display.Sprite));


See also

*
Reification (computer science) Reification is the process by which an abstract idea about a computer program is turned into an explicit data model or other object created in a programming language. A computable/addressable object—a resource—is created in a system as a prox ...
*
typeof typeof, alternately also typeOf, and TypeOf, is an operator provided by several programming languages to determine the data type of a variable. This is useful when constructing programs that must accept multiple types of data without explicitly sp ...


References


External links


Introspection
o
Rosetta Code
{{DEFAULTSORT:Type Introspection Object-oriented programming Articles with example C++ code fr:Introspection (informatique)