Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Type introspection

From Wikipedia, the free encyclopedia
(Redirected fromIntrospection (computer science))
Programming language feature
This article has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages)
This articlecontainsinstructions or advice. Wikipedia is not a guidebook; please helprewrite such content to be encyclopedic or move it toWikiversity,Wikibooks, orWikivoyage.(December 2011)
This articlemay containexcessive orirrelevant examples. Please helpimprove it by removingless pertinent examples andelaborating on existing ones.(December 2011) (Learn how and when to remove this message)
(Learn how and when to remove this message)

Incomputing,type introspection is the ability of a program toexamine thetype or properties of anobjectatruntime.Someprogramming languages possess this capability.

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

Examples

[edit]

C++

[edit]

C++ supports type introspection via therun-time type information (RTTI)typeid anddynamic cast keywords.Thedynamic_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){p->walk();}

Thetypeid operator retrieves astd::type_info object describing the most derived type of an object:

if(typeid(Person)==typeid(*obj)){serializePerson(obj);}

C#

[edit]

InC# introspection can be done using theis keyword. For instance:

if(objisPerson){// Do whatever you want}

Objective-C

[edit]

InObjective-C, for example, both the generic Object and NSObject (inCocoa/OpenStep) provide themethodisMemberOfClass: which returns true if the argument to the method is an instance of the specified class. The methodisKindOfClass: analogously returns true if the argument inherits from the specified class.

For example, say we have anApple and anOrange class inheriting fromFruit.

Now, in theeat method we can write

-(void)eat:(id)sth{if([sthisKindOfClass:[Fruitclass]]){// we're actually eating a Fruit, so continueif([sthisMemberOfClass:[Appleclass]]){eatApple(sth);}elseif([sthisMemberOfClass:[Orangeclass]]){eatOrange(sth);}else{error();}}else{error();}}

Now, wheneat is called with a generic object (anid), the function will behave correctly depending on the type of the generic object.

Object Pascal

[edit]

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 anis operator, to determine if an object is or descends from a given class, anas 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.

procedureForm1.MyButtonOnClick(Sender:TObject);varaButton:TButton;SenderClass:TClass;beginSenderClass:=Sender.ClassType;//returns Sender's class pointerifsenderisTButtonthenbeginaButton:=senderasTButton;EditBox.Text:=aButton.Caption;//Property that the button has but generic objects don'tendelsebeginEditBox.Text:=Sender.ClassName;//returns the name of Sender's class as a stringend;end;

Java

[edit]

The simplest example of type introspection in Java is theinstanceof[1] operator. Theinstanceof 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(objinstanceofPersonp){p.walk();}

Thejava.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 aparticular class),Object.getClass() andClass.getName() can be used:

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

PHP

[edit]

InPHP introspection can be done usinginstanceof operator. For instance:

if($objinstanceofPerson){// Do whatever you want}

Perl

[edit]

Introspection can be achieved using theref andisa functions inPerl.

We can introspect the following classes and their corresponding instances:

packageAnimal;subnew{my$class=shift;returnbless{},$class;}packageDog;usebase'Animal';packagemain;my$animal=Animal->new();my$dog=Dog->new();

using:

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

Meta-Object Protocol

[edit]

Much more powerful introspection in Perl can be achieved using theMoose object system[3] and theClass::MOPmeta-object protocol;[4] for example, you can check if a given objectdoes aroleX:

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:

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

Python

[edit]

The most common method of introspection inPython is using thedir function to detail the attributes of an object. For example:

classFoo:def__init__(self,val:int)->None:self.x=valdefget_x(self)->int:returnself.x
print(dir(Foo(5)))# prints ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'bar', 'x']

Also, the built-in functionstype andisinstance can be used to determine what an objectis whilehasattr can determine what an objectdoes. For example:

a:Foo=Foo(10)b:Bar=Bar(11)print(type(a))# prints <type 'Foo'>isinstance(a,Foo)# prints Trueprint(isinstance(a,type(a)))# prints Trueprint(isinstance(a,type(b)))# prints Falseprint(hasattr(a,'bar'))# prints True

Ruby

[edit]

Type introspection is a core feature ofRuby. In Ruby, the Object class (ancestor of every class) providesObject#instance_of? andObject#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 theInteractive Ruby Shell):

$ irbirb(main):001:0>A=Class.new=> Airb(main):002:0>B=Class.newA=> Birb(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=> trueirb(main):006:0>b.instance_of?A=> falseirb(main):007:0>b.kind_of?A=> true

In the example above, theClass class is used as any other class in Ruby. Two classes are created,A andB, the former is being a superclass of the latter, then one instance of each class is checked. The last expression gives true becauseA is a superclass of the class ofb.

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=> trueirb(main):009:0>a.class=> Airb(main):010:0>a.class.class=> Classirb(main):011:0>A>B=> trueirb(main):012:0>B<=A=> true

ActionScript

[edit]

InActionScript (as3), the functionflash.utils.getQualifiedClassName can be used to retrieve the class/type name of an arbitrary object.

// all classes used in as3 must be imported explicitlyimportflash.utils.getQualifiedClassName;importflash.display.Sprite;// trace is like System.out.println() in Java or echo in PHPtrace(getQualifiedClassName("I'm a String"));// "String"trace(getQualifiedClassName(1));// "int", see dynamic casting for why not Numbertrace(getQualifiedClassName(newSprite()));// "flash.display.Sprite"

Alternatively, the operatoris can be used to determine if an object is of a specific type:

// trace is like System.out.println() in Java or echo in PHPtrace("I'm a String"isString);// truetrace(1isString);// falsetrace("I'm a String"isNumber);// falsetrace(1isNumber);// true

This second function can be used to testclass inheritance parents as well:

importflash.display.DisplayObject;importflash.display.Sprite;// extends DisplayObjecttrace(newSprite()isSprite);// truetrace(newSprite()isDisplayObject);// true, because Sprite extends DisplayObjecttrace(newSprite()isString);// false

Meta-type introspection

[edit]

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 theflash.utils.describeType function; this is used when implementingreflection in ActionScript.

importflash.utils.describeType;importflash.utils.getDefinitionByName;importflash.utils.getQualifiedClassName;importflash.display.Sprite;varclassName:String=getQualifiedClassName(newSprite());// "flash.display.Sprite"varclassRef: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

[edit]

References

[edit]
  1. ^Java Language Specification: instanceof
  2. ^Java API: java.lang.Class
  3. ^Moose meta API documentation
  4. ^Class::MOP - a meta-object protocol for Perl

External links

[edit]

[[fr:Introspection (informatique)]

Retrieved from "https://en.wikipedia.org/w/index.php?title=Type_introspection&oldid=1315470092"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp