All Topics  
Reflection (computer science)

 

   Email Print
   Bookmark   Link






 

Reflection (computer science)



 
 
In computer science
Computer science

Computer 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

Computer programs are Instruction for a computer. A computer requires programs to function. Moreover, a computer program does not run unless its instructions are executed by a Central processing unit; however, a program may communicate an Algorithm#Formalization of algorithms to people without running....
 can observe and modify its own structure and behaviour. The programming paradigm driven by reflection is called reflective programming. It is a particular kind of 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 runtime that would otherwise be done at compile time....
.

In most modern computer architecture
Computer architecture

Computer architecture in computer engineering is the conceptual design and fundamental operational structure of a computer system. It is a blueprint and functional description of requirements and design implementations for the various parts of a computer, focusing largely on the way by which the central processing unit performs internally an...
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.






Discussion
Ask a question about 'Reflection (computer science)'
Start a new discussion about 'Reflection (computer science)'
Answer questions from other users
Full Discussion Forum



Encyclopedia


In computer science
Computer science

Computer 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

Computer programs are Instruction for a computer. A computer requires programs to function. Moreover, a computer program does not run unless its instructions are executed by a Central processing unit; however, a program may communicate an Algorithm#Formalization of algorithms to people without running....
 can observe and modify its own structure and behaviour. The programming paradigm driven by reflection is called reflective programming. It is a particular kind of 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 runtime that would otherwise be done at compile time....
.

In most modern computer architecture
Computer architecture

Computer architecture in computer engineering is the conceptual design and fundamental operational structure of a computer system. It is a blueprint and functional description of requirements and design implementations for the various parts of a computer, focusing largely on the way by which the central processing unit performs internally an...
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 programming, Type system, reflection computer programming 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 learning, at PARC by Al...
 and scripting language
Scripting language

A scripting language, script language or extension language, is a programming language that allows some control of a single or many Application software....
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 ....
 and C
C (programming language)

C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
.

Reflection-oriented programming

Reflection-oriented programming, or reflective programming, is a functional extension to the object-oriented programming paradigm. Reflection-oriented programming includes self-examination, self-modification, and self-replication. However, the emphasis of the reflection-oriented paradigm is dynamic program modification, which can be determined and executed at runtime. Some imperative
Imperative programming

In computer science, imperative programming is a programming paradigm that describes computation in terms of statement s that change a program state ....
 approaches, such as procedural and object-oriented programming paradigms, specify that there is an exact predetermined sequence of operations with which to process data. The reflection-oriented programming paradigm, however, adds that program instructions can be modified dynamically at runtime and invoked in their modified state. That is, the program architecture itself can be decided at runtime based upon the data, services, and specific operations that are applicable at runtime.

Programming sequences can be classified in one of two ways, atomic or compound. Atomic operations are those that can be viewed as completing in a single, logical step, such as the addition of two numbers. Compound operations are those that require a series of multiple atomic operations.

A compound statement, in classic procedural or object-oriented programming, can lose its structure once it is compiled. The reflective programming paradigm introduces the concept of meta-information
Metadata

Metadata is "data about other data", of any sort in any media. An item of metadata may describe an individual datum, or content item, or a collection of data including multiple content items and hierarchical levels, for example a database schema....
, which keeps knowledge of program structure. Meta-information stores information such as the name of the contained methods, the name of the class, the name of parent classes, and/or what the compound statement is supposed to do. Using this stored information, as an object is consumed (processed), it can be reflected upon to find out the operations that it supports. The operation that issues in the required state via the desired state transition can be chosen at run-time without hard-coding it.

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.

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 runtime that would otherwise be done at compile time....
.

Implementation

A language supporting reflection provides a number of features available at runtime that would otherwise be very obscure or impossible 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, class
    Class (computer science)

    In object-oriented programming, a class is a programming language construct that is used as a blueprint to create Object s. This blueprint includes Attribute s and Method s that the created objects all share....
    es, methods, protocols, etc.) as a first-class object
    First-class object

    In computing, a first-class object , in the context of a particular programming language, is an entity which can be used in programs without restriction ....
     at runtime.
  • Convert a string
    String (computer science)

    In computer programming and some branches of mathematics, a string is an ordered sequence of symbols. These symbols are chosen from a predetermined 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 Reflection , Object-oriented programming programming language which adds Smalltalk-style message passing to C .Today it is used primarily on Mac OS X, iPhone OS, and GNUstep, three environments based on the OpenStep standard, and is the primary language used for the NEXTSTEP, OpenStep#OPENSTEP, and Cocoa application framew...
 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 , a Reggae DJ *a DNA probe used in the selector-technique *a special kind of switch used in computers to connect multiple lines to a single line....
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 American National Standards Institute standard document Information Technology - Programming Language - Common Lisp, formerly X3.226-1994 ....
, 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 program and generates another program. It is often important that the derived program be semantically equivalent to the original, relative to a particular Formal semantics of programming languages....
 system to define automated source code changes.

Examples


C#

Here is an equivalent example in C#: //Without reflection Foo foo = new Foo; foo.Hello;

//With reflection Type t = Assembly.GetCallingAssembly.GetType("FooNamespace.Foo"); t.InvokeMember("Hello", BindingFlags.InvokeMethod, null, Activator.CreateInstance(t), null);

This next example demonstrates the use of advanced features of reflection. It loads an assembly
.NET assembly

In the Microsoft .NET software framework, an assembly is a partially compiler code library for use in deployment, versioning and security. In the Microsoft Windows implementation of .NET, an assembly is a PE file for Windows GUI on Intel x86....
 (which can be thought of as a class library) dynamically and uses reflection to find the methods that take no parameters and figure out whether it was recently modified or not. To decide whether a method was recently modified or not, it uses a custom attribute
.NET metadata

.NET metadata, in the Microsoft .NET framework, refers to certain data structures embedded within the Common Intermediate Language code that describes the high-level structure of the code....
 RecentlyModified which the developer tags the methods with. Presence of the attribute indicates it was recently modified. An attribute is itself implemented as a class, that derives from the Attribute class.

The program loads the assembly dynamically at runtime, and checks that the assembly supports the RecentlyModified attribute. This check is facilitated by using another custom attribute on the entire assembly: SupportsRecentlyModified. If it is supported, names of all the methods are then retrieved. For each method, objects representing all its parameters as well as the objects representing the RecentlyAttribute are retrieved. If the attribute retrieval succeeds and the parameter retrieval fails (indicating presence of the attribute but absence of any parameters), a match has been found.

Definition of the custom attributes: //RecentlyModified: Applicable only to methods. //SupportsRecentlyModified: Applicable to the entire assembly.

[AttributeUsage(AttributeTargets.Method, AllowMultiple=false)] class RecentlyModifiedAttribute : Attribute

[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)] class SupportsRecentlyModifiedAttribute : Attribute



Implementation of the method filter: static void Main(string[] args)



C++

Although the language itself does not provide any support for reflection, there are some attempts based on templates, RTTI information, using debug information provided by the compiler, or even patching the GNU compiler to provide extra information.

Common Lisp

Here is an equivalent example in Common Lisp
Common Lisp

Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in American National Standards Institute standard document Information Technology - Programming Language - Common Lisp, formerly X3.226-1994 ....
: ;Without reflection (hello)

;With reflection (funcall (read-from-string "HELLO"))

;or (funcall (symbol-function (intern "HELLO"))) However, this works only for symbols in topmost lexical environment (or dynamic one). A better example, using CLOS, is: ;Method hello is called on instance of class foo. (hello (make-instance 'foo))

;or (hello (make-instance (find-class 'foo)) This code is equivalent to Java's one. Common Lisp, like Scheme, is able to transform lists into functions or procedures. This is the source of the Lisp macro ability to change the code behavior (including from other macros) during (and after) compilation.

ECMAScript (JavaScript)

Here is an equivalent example in ECMAScript
ECMAScript

ECMAScript is a scripting language, standardized by Ecma International in the ECMA-262 Specification . The language is widely used on the World Wide Web, and is often confused with JavaScript or JScript, the two major Programming language dialect from which ECMAScript was standardized....
: // 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 ....
 using the Java package
Java package

A Java package is a mechanism for organizing Java class into namespace 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....
 . Consider two pieces of code // Without reflection Foo foo = new Foo; foo.hello;

// With reflection Class cls = Class.forName("Foo"); Object foo = cls.newInstance; Method method = cls.getMethod("hello", null); method.invoke(foo, null); Both code fragments create an instance of a class Foo and call its hello method. The difference is that, in the first fragment, the names of the class and method are hard-coded; it is not possible to use a class of another name. In the second fragment, the names of the class and method can easily be made to vary at runtime
Runtime

In computer science, runtime or run time describes the operation of a computer program, the duration of its execution, from beginning to termination ....
. The downside is that the second version is harder to read, and is not protected by compile-time syntax and semantic checking. For example, if no class Foo exists, an error will be generated at compile time for the first version. The equivalent error will only be generated at run time for the second version.

Perl

Here is an equivalent example in Perl
Perl

In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
:
  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 scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface....
 (check the ).

This is the non-reflective way to invoke Foohello: $Foo = new Foo; $Foo->hello;

Using reflection the class and method are retrieved as reflection objects and then used to create a new instance and invoke the method. $f = new ReflectionClass("Foo"); $m = $f->GetMethod("hello"); $m->invoke( $f->newInstance );

Although the above is the ideal way of doing it, it can also be easily be done as follows: $class = "Foo"; $method = "hello"; $object = new $class; $object->$method;

Python

Here is an equivalent example from the Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
 shell. Reflection is an important part of Python and there are several ways it can be achieved, many of which do not include the use of the eval
Eval

In some programming languages, eval is a subroutine which evaluates a string as though it were an expression and returns a result; in others, it executes multiple lines of code as though they had been included instead of the line including the eval....
function and its attendant security risks: >>> # Class definition >>> class Foo(object): ... def hello(self): ... print "Hi" ... >>> # Instantiation >>> foo = Foo >>> # Normal call >>> foo.hello Hi >>> # Evaluate a string in the context of the global namespace >>> eval("foo.hello", globals) Hi >>> # Interpret distinct instance & method names from strings >>> instancename = 'foo' >>> methodname = 'hello' >>> instance = globals[instancename] >>> method = getattr(instance , methodname) >>> method Hi >>> # or get a method from class not from object >>> classfoo = type(instance) >>> unboundmethod= getattr(classfoo , methodname) >>> unboundmethod(instance) Hi

Ruby

Here is an equivalent example in Ruby
Ruby (programming language)

Ruby is a dynamic programming language, reflection , general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features....
:
  1. without reflection
Foo.new.hello

  1. with reflection
Object.const_get(:Foo).new.send(:hello)

Smalltalk

Here is an equivalent example in Smalltalk
Smalltalk

Smalltalk is an Object-oriented programming, Type system, reflection computer programming 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 learning, at PARC by Al...
:

"Without reflection" Foo new hello

"With reflection" (Compiler evaluate: 'Foo') new perform: #hello

The class name and the method name will often be stored in variables and in practice runtime checks need to be made to ensure that it is safe to perform the operations:

"With reflection"

| x y className methodName |

className := 'Foo'. methodName := 'hello'.

x := (Compiler evaluate: className).

(x isKindOf: Class) ifTrue: [ y := x new.

(y respondsTo: methodName asSymbol) ifTrue: [ y perform: methodName asSymbol ] ]

Smalltalk also makes use of blocks of compiled code that are passed around as objects. This means that generalised frameworks can be given variations in behavior for them to execute. Blocks allow delayed and conditional execution. They can be parameterised. (Blocks are implemented by the class BlockClosure).

X := [ :op | 99 perform: op with: 1]. ".....then later we can execute either of:" X value: #+ "which gives 100, or" X value: #- "which gives 98."

See also

  • Type introspection
    Type introspection

    In computing, type introspection is a capability of some object-oriented programming programming languages to determine the type of an Object at runtime....
  • Self-modifying code
    Self-modifying code

    In computer science, self-modifying code is Code that alters its own Instruction while it is Execution - usually to reduce the instruction path length and improve performance....
  • 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 ....
    s
  • List of reflective programming languages and platforms
    List of reflective programming languages and platforms

    Programming languages and platforms that typically support Reflection include dynamically typed languages such as Objective-C and Smalltalk; scripting languages such as Perl, PHP, Python , VBScript, and JavaScript; and the Maude system of rewriting logic....


Further reading

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


External links

  • (Citeseer
    CiteSeer

    CiteSeer is a public Search engine and digital library for scientific and academic papers. It was created by researchers Steve_Lawrence_, Kurt Bollacker and Lee Giles while they were at the NEC Research Institute , Princeton, New Jersey, USA....
     page).
  • A reflection library for C++.


  • from Sun Microsystems
  • By Jakob Jenkov