Reflection (computer science)
Encyclopedia
In computer science
Computer science
Computer science or computing science is the study of the theoretical foundations of information and computation and of practical techniques for their implementation and application in computer systems...

, reflection is the process by which a computer program
Computer program
A computer program is a sequence of instructions written to perform a specified task with a computer. A computer requires programs to function, typically executing the program's instructions in a central processor. The program has an executable form that the computer can use directly to execute...

 can observe (do type introspection
Type introspection
In computing, type introspection is a capability of some object-oriented programming languages to determine the type of an object at runtime. This is a notable capability of the Objective-C language, and is a common feature in any language that allows object classes to be manipulated as first-class...

) and modify its own structure and behavior at runtime.

In many computer architecture
Computer architecture
In computer science and engineering, computer architecture is the practical art of selecting and interconnecting hardware components to create computers that meet functional, performance and cost goals and the formal modelling of those systems....

s, program instructions are stored as data—hence the distinction between instruction and data is merely a matter of how the information is treated by the computer and programming language. Normally, instructions are executed and data is processed; however, in some languages, programs can also treat instructions as data and therefore make reflective modifications. Reflection is most commonly used in high-level virtual machine programming languages like Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...

 and scripting language
Scripting language
A scripting language, script language, or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the...

s, and less commonly used in manifestly typed
Manifest typing
In computer science, manifest typing is when the software programmer explicitly identifies the type of each variable being declared. For example: if variable X is going to store integers then its type must be declared as integer....

 and/or statically typed programming languages such as Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

, C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

, ML or Haskell
Haskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...

.

Historical background

Brian Cantwell Smith
Brian Cantwell Smith
Brian Cantwell Smith is a scholar in the fields of cognitive science, computer science, information studies, and philosophy, especially ontology. His research has focused on the foundations and philosophy of computing, both in the practice and theory of computer science, and in the use of...

's 1982 doctoral dissertation introduced the notion of computational reflection in programming languages, and the notion of the meta-circular interpreter as a component of 3-Lisp.

Uses

Reflection can be used for observing and/or modifying program execution at runtime. A reflection-oriented program component can monitor the execution of an enclosure of code and can modify itself according to a desired goal related to that enclosure. This is typically accomplished by dynamically assigning program code at runtime.

In object oriented programing languages such as Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

, reflection allows inspection of classes, interfaces, fields and methods at runtime without knowing the names of the interfaces, fields, methods at compile time. It also allows instantiation of new objects and invocation of methods.

Reflection can also be used to adapt a given program to different situations dynamically. For example, consider an application that uses two different classes X and Y interchangeably to perform similar operations. Without reflection-oriented programming, the application might be hard-coded to call method names of class X and class Y. However, using the reflection-oriented programming paradigm, the application could be designed and written to utilize reflection in order to invoke methods in classes X and Y without hard-coding method names. Reflection-oriented programming almost always requires additional knowledge, framework, relational mapping, and object relevance in order to take advantage of more generic code execution. Hard-coding can be avoided to the extent that reflection-oriented programming is used.

Reflection is also a key strategy for metaprogramming
Metaprogramming
Metaprogramming is the writing of computer programs that write or manipulate other programs as their data, or that do part of the work at compile time that would otherwise be done at runtime...

.

Implementation

A language supporting reflection provides a number of features available at runtime that would otherwise be very obscure to accomplish in a lower-level language. Some of these features are the abilities to:
  • Discover and modify source code constructions (such as code blocks, classes
    Class (computer science)
    In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...

    , methods, protocols, etc.) as a 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...

     at runtime.
  • Convert a string
    String (computer science)
    In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet....

     matching the symbolic name of a class or function into a reference to or invocation of that class or function.
  • Evaluate a string as if it were a source code statement at runtime.
  • Create a new interpreter for the language's bytecode to give a new meaning or purpose for a programming construct.


These features can be implemented in different ways. In MOO, reflection forms a natural part of everyday programming idiom. When verbs (methods) are called, various variables such as verb (the name of the verb being called) and this (the object on which the verb is called) are populated to give the context of the call. Security is typically managed by accessing the caller stack programmatically: Since callers is a list of the methods by which the current verb was eventually called, performing tests on callers[1] (the command invoked by the original user) allows the verb to protect itself against unauthorised use.

Compiled languages rely on their runtime system to provide information about the source code. A compiled 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...

 executable, for example, records the names of all methods in a block of the executable, providing a table to correspond these with the underlying methods (or selector
Selector
A selector can be:*"Selector" music scheduling software for radio stations created by Radio Computing Services*Selector , a Reggae DJ *A DNA probe used in the selector-technique...

s for these methods) compiled into the program. In a compiled language that supports runtime creation of functions, such as Common Lisp
Common Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...

, the runtime environment must include a compiler or an interpreter.

Reflection can be implemented for languages not having built-in reflection facilities by using a program transformation
Program transformation
A program transformation is any operation that takes a computer program and generates another program. In many cases the transformed program is required to be semantically equivalent to the original, relative to a particular formal semantics and in fewer cases the transformations result in programs...

 system to define automated source code changes.

Examples

The following examples show an instance
Instance (computer science)
In object-oriented programming an instance is an occurrence or a copy of an object, whether currently executing or not. Instances of a class share the same set of attributes, yet will typically differ in what those attributes contain....

 foo of a class
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...

 Foo being created, and a 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...

 hello (or Hello) of the instance being called. For each 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....

, two versions are shown; the first being a call sequence without reflection and the second using reflection to access the class and the method.

C#

Here is an example in C#:

//Without reflection
Foo foo = new Foo;
foo.Hello;
--
//With reflection
object foo = Activator.CreateInstance(null, "Foo");
foo.GetType.GetMethod("Hello").Invoke(foo, null);

VB.NET

Here is an example in VB.NET:

'Without reflection
Dim foo As New Foo
foo.Hello
--
'With reflection
Dim foo = Activator.CreateInstance(Nothing, "Foo")
foo.GetType.GetMethod("Hello").Invoke(foo, Nothing)

Visual Basic

Here is an example in VisualBasic:

'Without reflection
Dim foo As New Foo
foo.Hello

'Using variable syntax
Dim foo As New Foo
Microsoft.VisualBasic.CallByName(foo, "Hello", CallType.Method)

ECMAScript

Here is an equivalent example in ECMAScript
ECMAScript
ECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript, and ActionScript.- History :JavaScript...

, and therefore works in JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

 and 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...

:

// Without reflection
new Foo.hello

// With reflection

// assuming that Foo resides in this
new this['Foo']['hello']

// or without assumption
new (eval('Foo'))['hello']

Java

The following is an example in Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 using the Java package
Java package
A Java package is a mechanism for organizing Java classes into namespaces similar to the modules of Modula. Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time...

 :
// Without reflection
new Foo.hello;

// With reflection
Class cls = Class.forName("Foo");
cls.getMethod("hello").invoke(cls.newInstance);

Delphi

This Delphi example assumes a TFoo class has been declared in a unit called Unit1:

uses RTTI, Unit1;

procedure WithoutReflection;
var
Foo: TFoo;
begin
Foo := TFoo.Create;
try
Foo.Hello;
finally
Foo.Free;
end;
end;

procedure WithReflection;
var
RttiContext: TRttiContext;
RttiType: TRttiInstanceType;
Foo: TObject;
begin
RttiType := RttiContext.FindType('Unit1.TFoo') as TRttiInstanceType;
Foo := RttiType.GetMethod('Create').Invoke(RttiType.MetaclassType, []).AsObject;
try
RttiType.GetMethod('Hello').Invoke(Foo, []);
finally
Foo.Free;
end;
end;

Qt/C++

Qt framework extends C++ with its meta-language and provides reflection ability of member/method reference and query by name for Qt objects with QMetaObject class, which contains meta-information about the Qt objects.

Lua

The following is an example in Lua

-- without reflection
Foo.hello

-- with reflection
_G['Foo']['hello']

Objective-C

The following is an example 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...


// Without reflection
Foo *foo = oo alloc] init];
[foo hello];

// With reflection
Class cls = NSClassFromString(@"Foo");
id foo = ls alloc] init];
SEL selector = NSSelectorFromString(@"hello");
[foo performSelector:selector withObject:nil];

Perl

Here is an equivalent example 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...

:
  1. without reflection

my $foo = Foo->new;
$foo->hello;
  1. with reflection

my $class = "Foo";
my $method = "hello";
my $object = $class->new;
$object->$method;

PHP

Here is an equivalent example 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...

:


// without reflection
$foo = new Foo;
$foo->hello;

// with reflection
$reflector = new ReflectionClass('Foo');
$foo = $reflector->newInstance;
$hello = $reflector->getMethod('hello');
$hello->invoke($foo);

// using callback
$foo = new Foo;
call_user_func(array($foo, 'hello'));

// using variable variables syntax
$className = 'Foo';
$foo = new $className;
$method = 'hello';
$foo->$method;

Python

Here is an equivalent example 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...

:
  1. without reflection

Foo.hello
  1. with reflection

getattr(globals['Foo'], 'hello')

Ruby

Here is an equivalent example in 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...

:
  1. without reflection

Foo.new.hello
  1. with reflection

Object.const_get(:Foo).send(:new).send(:hello)

e

Here is an equivalent example in e
E (verification language)
e is a hardware verification language which is tailored to implementing highly flexible and reusable verification testbenches.- History :...

:
  1. without reflection

var foo : Foo = new;
foo.hello;
  1. with reflection

rf_manager.get_type_by_name(foo).get_method("hello").invoke(foo);

Smalltalk

Here is an equivalent example in Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...

:


"Without reflection"
Foo new hello

"With reflection"
((Smalltalk at: #Foo) perform: #new) perform: #hello

Io

Here is an equivalent example in Io
Io (programming language)
Io is a pure object-oriented programming language inspired by Smalltalk, Self, Lua, Lisp, Act1, and NewtonScript. Io has a prototype-based object model similar to the ones in Self and NewtonScript, eliminating the distinction between instance and class. Like Smalltalk, everything is an object and...

:


Foo := Object clone do(
hello := method(
"Hello" println
)
)
  1. Without reflection

Foo hello
  1. With reflection

getSlot("Foo") getSlot("hello") call

ActionScript 3.0

Here is an equivalent example 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...

:


//Without reflection
var foo:Foo = new Foo;
foo.hello;

//With reflection
var cls:Object = getDefinitionByName("Foo");
var foo:Object = new cls;
foo["hello"];

See also

  • Type introspection
    Type introspection
    In computing, type introspection is a capability of some object-oriented programming languages to determine the type of an object at runtime. This is a notable capability of the Objective-C language, and is a common feature in any language that allows object classes to be manipulated as first-class...

  • Self-modifying code
    Self-modifying code
    In computer science, self-modifying code is code that alters its own instructions while it is executing - usually to reduce the instruction path length and improve performance or simply to reduce otherwise repetitively similar code, thus simplifying maintenance...

  • Programming paradigm
    Programming paradigm
    A programming paradigm is a fundamental style of computer programming. Paradigms differ in the concepts and abstractions used to represent the elements of a program and the steps that compose a computation A programming paradigm is a fundamental style of computer programming. (Compare with a...

    s
  • List of reflective programming languages and platforms

Further reading

  • Ira R. Forman and Nate Forman, Java Reflection in Action (2005), ISBN 1-932394-18-4
  • Ira R. Forman and Scott Danforth, Putting Metaclasses to Work (1999), ISBN 0-201-43305-2

External links

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