Type introspection

In computing, type introspection is the ability of a program to examine the type or properties of an object at runtime. Some programming languages possess this capability.

Introspection should not be confused with reflection, which goes a step further and is the ability for a program to manipulate the metadata, properties, and functions of an object at runtime. Some programming languages also possess that capability (e.g., Java, Python, Julia, and Go).

Examples

Objective-C

In Objective-C, for example, both the generic Object and NSObject (in Cocoa/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 an Apple and an Orange class inheriting from Fruit.

Now, in the eat method we can write

- (void)eat:(id)sth {
    if ([sth isKindOfClass:[Fruit class]]) {
        // we're actually eating a Fruit, so continue
        if ([sth isMemberOfClass:[Apple class]]) {
            eatApple(sth);
        } else if ([sth isMemberOfClass:[Orange class]]) {
            eatOrange(sth);
        } else {
            error();
        }
    } else {
        error();
    }
}

Now, when eat 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 run-time type information (RTTI) typeid and dynamic cast keywords. The dynamic_cast expression can be used to determine whether a particular object is of a particular derived class. For instance:

Person* p = dynamic_cast<Person *>(obj);
if (p != nullptr) {
  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. 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 instanceof[1] 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[2] 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 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.

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 object system[3] and the Class::MOP meta-object protocol;[4] for example, 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 is using the dir 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 type and isinstance can be used to determine what an object is while hasattr can determine what an object does. For example:

>>> a = Foo(10)
>>> b = Bar(11)
>>> type(a)
<type 'Foo'>
>>> isinstance(a, Foo)
True
>>> isinstance(a, type(a))
True
>>> isinstance(a, type(b))
False
>>> hasattr(a, 'bar')
True

Ruby

Type introspection is a core feature of Ruby. 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. For example, consider the following example code (you can immediately try this with the Interactive Ruby Shell):

$ 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
=> #<A:0x2e44b78>
irb(main):004:0> b=B.new
=> #<B:0x2e431b0>
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 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.

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

ActionScript

In ActionScript (as3), 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.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 is 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 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 function; this is used when implementing reflection 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{{Not a typo|.}}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));

See also

References

Read other articles:

Santo CybiDinding Cybi di Holyhead, AngleseyAbbas Caer-GybiLahir483[1]Cornwall, InggrisMeninggal8 November 555Dihormati diPersekutuan AnglikanGereja Katolik RomaKanonisasiPra-KongregasiPesta8 November13 Agustus di CornwallPelindungCuby, CornwallLandulph, CornwallLlangibby, Monmouthshire, WalesLlangybi, Cardigan, WalesTregony, CornwallKenwyn, Cornwall Cybi (dalam bahasa Wales) atau Cuby (dalam bahasa Kernowek) merupakan seorang uskup, santo dan secara singkat, raja asal Kernowyon pada ...

 

كرة القدم في دورة الألعاب العربية 1953معلومات عامةجزء من دورة الألعاب العربية 1953 الرياضة كرة القدم المكان الإسكندرية بتاريخ 1953 عدد المباريات 9 كرة القدم في الدورة الرياضية العربية الثانية بيروت 1957 تعديل - تعديل مصدري - تعديل ويكي بيانات نظام البطولة اشترك في المسابقة ست منتخ...

 

هذه المقالة بحاجة لمراجعة خبير مختص في مجالها. يرجى من المختصين في مجالها مراجعتها وتطويرها. المقالة بحاجة لمراجعة فالجهاز ليس مقاومة متغيرة رقمية وقد تم مراجعة المقالة الاصلية بالاضافة إلى مواقع اجنبية واتضح ان الجهاز عبارة عن مقياس لا مقاومة. مقاومة متغيرة رقمية (بالإنج...

TinianTinian dalam peta, barat daya dari Saipan.TinianGeografiLokasiSamudera PasifikKoordinat15°00′N 145°38′E / 15.000°N 145.633°E / 15.000; 145.633Koordinat: 15°00′N 145°38′E / 15.000°N 145.633°E / 15.000; 145.633KepulauanKepulauan MarianaLuas101,22 km2Titik tertinggiGunung Lasso (171 m)PemerintahanNegaraAmerika SerikatPersemakmuranKepulauan Mariana UtaraKota terbesarSan JoseKependudukanPenduduk3.136 jiw...

 

1995 novel by Nicola Griffith This article is about the science fiction book. For the record label, see Slow River Records. Slow River Cover of first edition (hardcover)AuthorNicola GriffithCover artistDaniel Furon and Robert OldingCountryUnited KingdomLanguageEnglishGenreScience fictionPublisherDel Rey BooksPublication date1995Media typePrint (Hardcover & Paperback)Pages343ISBN0-345-39165-9OCLC32013101Dewey Decimal813/.54 20LC ClassPS3557.R48935 S58 1995 Slow River is a sc...

 

Stadion VIJInformasi stadionNama lamaVijveldPemilikPemerintah Provinsi DKI JakartaLokasiLokasiCideng, Gambir, Jakarta Pusat, IndonesiaKoordinat6°10′12.8510″S 106°48′19.2676″E / 6.170236389°S 106.805352111°E / -6.170236389; 106.805352111Transportasi umum8 RS TarakanData teknisPermukaanRumputKapasitas500PemakaiPersija Jakarta (1928–1950)Sunting kotak info • L • BBantuan penggunaan templat ini Stadion VIJ (Belanda: Vijveldcode: nl is deprecated...

Komando Resor Militer 042/Garuda PutihDibentuk10 November 1959Negara IndonesiaCabangTNI Angkatan DaratTipe unitKorem Tipe APeranSatuan TeritorialBagian dariKodam II/SriwijayaMakoremJambi, JambiPelindungTentara Nasional IndonesiaMotoPengabdian Tanpa BatasBaret H I J A U Ulang tahun10 NovemberSitus webkorem-042-gapu.mil.idTokohKomandanBrigjen. TNI RachmadKepala StafKolonel Inf Edi Basuki Komando Resor Militer 042/Garuda Putih atau biasa disingkat Korem 042/Gapu adalah salah satu ...

 

Spanish water polo player In this Spanish name, the first or paternal surname is Estiarte and the second or maternal family name is Duocastella. Manuel Estiarte Manuel Estiarte in 2009Personal informationFull name Manel Estiarte DuocastellaBorn 26 October 1961 (1961-10-26) (age 62)Manresa, SpainNationality  SpainHeight 178 cm (5 ft 10 in)Weight 62 kg (137 lb)National teamYears Team1977–2000  Spain Medal record Men's water polo Repres...

 

1697 naval battle of the Nine Years' War This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Battle of Hudson's Bay – news · newspapers · books · scholar · JSTOR (August 2022) (Learn how and when to remove this message) For the 1782 raid by Jean-François de Galaup, comte de La Pérouse, see Hudson Bay Expeditio...

Bus operator in North Yorkshire, England Van Hool bodied Scania K114IB coach York Pullman[1] is a bus operating company based in Rufforth, North Yorkshire, England. The first company to use the Pullman name was founded in 1926 by Norman Pearce and Hartas Foxton. The Yorkshire Pullman remained in use until the company was deregistered in 2000. In 2007 haulage firm K&J Logistics revived the name for use on its excursion programme and open-top tour of York. This reconstituted company...

 

2007 television film directed by Paul Hoen For the song by M.I.A, see AIM (album). For the song by A-Mei Chang, see Jump In (A-Mei Chang song). Jump In!Promotional posterWritten byDoreen Spicer-DannellyRegina Y. HicksKarin GistDirected byPaul HoenStarringCorbin BleuKeke PalmerDavid ReiversLaivan GreeneShanica KnowlesKylee RussellNarrated byPatrick Johnson Jr.Theme music composerFrank FitzpatrickCountry of originUnited StatesCanadaOriginal languageEnglishProductionProducersKevin LaffertyJohn D...

 

Pour l’article homonyme, voir Lacerte. Charles Gérin-LajoieCharles Gérin-LajoieFonctionDéputé à la Chambre des communes du CanadaSaint-Maurice22 janvier 1874 - 16 septembre 1878Élie LacerteLouis-Léon Lesieur-DésaulniersBiographieNaissance 28 décembre 1824YamachicheDécès 6 novembre 1895 (à 70 ans)Trois-RivièresNationalité canadienneActivité Homme politiqueAutres informationsPartis politiques Parti libéral du CanadaParti rougemodifier - modifier le code - modifier Wikida...

British docudrama television series (1992–2003) For the 2012 factual programme, see 999: What's Your Emergency? 999GenreDocudramaCreated byPeter SalmonBased onRescue 911Presented byMichael BuerkFiona FosterJuliet MorrisDonna BernardCatherine HoodCountry of originUnited KingdomOriginal languageEnglishNo. of series125 (Lifesavers)1 (International)No. of episodes10341 (Lifesavers)6 (International)20 (Specials)ProductionRunning time50 minutesOriginal releaseNetworkBBC OneRelease25 June 1992...

 

Regulatory Body A major contributor to this article appears to have a close connection with its subject. It may require cleanup to comply with Wikipedia's content policies, particularly neutral point of view. Please discuss further on the talk page. (June 2018) (Learn how and when to remove this message) Small Industries Development Bank of India (SIDBI)Agency overviewFormed2 April 1990; 34 years ago (1990-04-02)TypeRegulatory BodyJurisdictionMinistry of Finance , Government...

 

This article relies excessively on references to primary sources. Please improve this article by adding secondary or tertiary sources. Find sources: Diving at the 2010 Commonwealth Games – Women's synchronised 10 metre platform – news · newspapers · books · scholar · JSTOR (July 2022) (Learn how and when to remove this message) Diving at the2010 Commonwealth GamesIndividual1 m Springboardmenwomen3 m Springboardmenwomen10 m platformmenwomenSynchronis...

EHESS École des hautes études en sciences sociales (EHESS) adalah salah satu Grandes écoles ilmu sosial paling selektif dan bergengsi di Paris, Prancis.[1] EHESS awalnya adalah departemen École pratique des hautes études, yang didirikan pada tahun 1868 untuk melatih para peneliti akademis. Ini menjadi lembaga independen pada tahun 1975. Saat ini, penelitiannya mencakup bidang ekonomi dan keuangan, ilmu kognitif, humaniora, dan politik, seperti sains, matematika terapan dan statis...

 

أوسكار روبرتسون معلومات شخصية اسم الولادة (بالإنجليزية: Oscar Palmer Robertson)‏  الميلاد 24 نوفمبر 1938 (العمر 85 سنة)شارلوت الطول 6 قدم 5 بوصة (2.0 م) مركز اللعب هجوم خلفي،  ومدافع مسدد الهدف  الإقامة إنديانابوليستينيسيشارلوت  الجنسية  الولايات المتحدة العرق أمريكي أ...

 

Sanskrit Hindu text For other uses, see Bhagavata Puranas (disambiguation). Not to be confused with Devi-Bhagavata Purana or Bhagavad Gita. Bhagavata Purana manuscripts from 16th to 19th century, in Sanskrit (above) and in Bengali Part of a series onVaishnavism Supreme deity Vishnu / Krishna / Rama Important deities Dashavatara Matsya Kurma Varaha Narasimha Vamana Parasurama Rama Balarama Krishna Buddha Kalki Other forms Dhanvantari Guruvayurappan Hayagriva Jagannath Mohini Nara-Narayana Prit...

Questa voce sull'argomento stagioni delle società calcistiche italiane è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Segui i suggerimenti del progetto di riferimento. Associazione Calcio IntraStagione 1933-1934Sport calcio Squadra Verbania Sportiva Prima Divisione6º posto nel girone C 1932-1933 1934-1935 Si invita a seguire il modello di voce Questa pagina raccoglie i dati riguardanti l'Associazione Calcio Intra nelle competizioni ufficiali d...

 

German theologian Gottlob Christian Storr Gottlob Christian Storr (10 September 1746 – 17 January 1805) was a German Protestant theologian, born in Stuttgart. He was the son of theologian Johann Christian Storr (1712–1773) and the older brother of naturalist Gottlieb Conrad Christian Storr (1749–1821). Biography Storr studied philosophy and theology at the University of Tübingen, where his instructors were Jeremias Friedrich Reuß (1700–1777) and Johann Friedrich Cotta (1701–1779)....