Reflection (computer science)
From Wikipedia, the free encyclopedia
This article needs additional citations for verification. Please help improve this article by adding reliable references (ideally, using inline citations). Unsourced material may be challenged and removed. (January 2008) |
Programming paradigms |
---|
|
In computer science, reflection is the process by which a computer program 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.
In many computer architectures, 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 and scripting languages, and less commonly used in manifestly typed and/or statically typed programming languages such as Java and C.
Contents |
[edit] 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 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, 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.
[edit] 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.
[edit] 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, classes, methods, protocols, etc.) as a first-class object at runtime.
- Convert a string 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 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 selectors for these methods) compiled into the program. In a compiled language that supports runtime creation of functions, such as Common Lisp, 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 system to define automated source code changes.
[edit] Examples
[edit] C#
Here is an example in C#:
//Without reflection Foo foo = new Foo(); foo.Hello(); //With reflection Type t = this.GetType("FooNamespace.Foo"); t.InvokeMember("Hello", BindingFlags.InvokeMethod, null, Activator.CreateInstance(t), null);
[edit] Common Lisp
Here is an equivalent example in Common Lisp:
;;Without reflection (hello) ;;With reflection (funcall (read-from-string "HELLO")) ;;or (funcall (symbol-function (intern "HELLO")))
[edit] ECMAScript
Here is an equivalent example in ECMAScript:
// Without reflection new Foo().hello() // With reflection // assuming that Foo resides in this new this['Foo']()['hello']() // or without assumption new (eval('Foo'))()['hello']()
[edit] Java
The following is an example in Java using the Java package java.lang.reflect
:
// 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);
[edit] Perl
Here is an equivalent example in Perl:
# without reflection my $foo = Foo->new(); $foo->hello(); # with reflection my $class = "Foo"; my $method = "hello"; my $object = $class->new(); $object->$method();
[edit] PHP
Here is an equivalent example in PHP:
// without reflection $Foo = new Foo(); $Foo->hello(); // with reflection $f = new ReflectionClass("Foo"); $m = $f->GetMethod("hello"); $m->invoke( $f->newInstance() );
[edit] Python
Here is an equivalent example from the Python shell:
>>> # Class definition >>> class Foo(object): ... def hello(self): ... print "Hi" ... >>> # Instantiation >>> foo = Foo() >>> # Normal call >>> foo.hello() Hi >>> # Call foo's hello() method using a string for the function name >>> method = getattr(foo, 'hello') >>> method() Hi
[edit] Ruby
Here is an equivalent example in Ruby:
# without reflection Foo.new.hello # with reflection Object.const_get(:Foo).new.send(:hello)
[edit] Smalltalk
Here is an equivalent example in Smalltalk:
"Without reflection" Foo new hello "With reflection" (Compiler evaluate: 'Foo') new perform: #hello
[edit] See also
- Type introspection
- Self-modifying code
- Programming paradigms
- List of reflective programming languages and platforms
[edit] References
- Jonathan M. Sobel and Daniel P. Friedman. An Introduction to Reflection-Oriented Programming (1996), Indiana University.
[edit] 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
[edit] External links
- Reflection in logic, functional and object-oriented programming: a short comparative study
- An Introduction to Reflection-Oriented Programming
- Reflection in C++
- Brian Foote's pages on Reflection in Smalltalk
- Java Reflection Tutorial from Sun Microsystems
|