Reflection (computer programming)
In computer science, reflection is the ability of a computer program to examine (see type introspection) and modify the structure and behavior (specifically the values, meta-data, properties and functions) of an object at runtime.
Reflection is most commonly used in high-level virtual machine programming languages like Smalltalk and scripting languages and also in manifestly typed or statically typed programming languages such as Java, ML, Haskell, C# and Scala.
The earliest computers were programmed in their native assembly language, which were inherently reflective as these original architectures could be programmed by defining instructions as data and using self-modifying code. As programming moved to higher level languages such as C, this reflective ability disappeared (outside of malware) until programming languages with reflection built in to their type systems appeared.
Brian Cantwell Smith'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.
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, 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
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
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.
|This section does not cite any references or sources. (January 2008)|
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, 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() (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.
// Without reflection new Foo().hello() // With reflection // assuming that Foo resides in this new this['Foo']()['hello']() // or without assumption new (eval('Foo'))()['hello']() // or simply eval('new Foo().hello()')
// Without reflection new Foo().hello(); // With reflection Class<?> fooClass = Class.forName("Foo"); fooClass.getMethod("hello").invoke(fooClass.newInstance());
The following is an example in PHP:
// 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();
// Foo class. @interface Foo : NSObject - (void)hello; @end // Sending "hello" to a Foo instance without reflection. Foo *obj = [[Foo alloc] init]; [obj hello]; // Sending "hello" to a Foo instance with reflection. id obj = [[NSClassFromString(@"Foo") alloc] init]; [obj performSelector: @selector(hello)];
The following is an example in R:
# Without reflection, assuming foo() returns a list or S3-type object foo()$hello() # With reflection eval(parse(text = "foo()$hello()"))
The following is an example in Ruby:
# without reflection obj = Foo.new obj.hello # with reflection class_name = "Foo" method = :hello obj = Kernel.const_get(class_name).new obj.send method # with eval eval "Foo.new().hello"
The following is an example in Python:
# without reflection obj = Foo() obj.hello() # with reflection class_name = "Foo" method = "hello" obj = globals()[class_name]() getattr(obj, method)() # with eval eval("Foo().hello()")
- Type introspection
- Self-modifying code
- Programming paradigms
- List of reflective programming languages and platforms
- Mirror (programming)
- A Tutorial on Behavioral Reflection and its Implementation by Matt Hurlbutt
- Brian Cantwell Smith, Procedural Reflection in Programming Languages, Department of Electrical Engineering and Computer Science, Massachusetts Institute of Technology, PhD Thesis, 1982.
- Brian C. Smith. Reflection and semantics in a procedural language. Technical Report MIT-LCS-TR-272, Massachusetts Institute of Technology, Cambridge, Mass., January 1982.
- Jonathan M. Sobel and Daniel P. Friedman. An Introduction to Reflection-Oriented Programming (1996), Indiana University.
- 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
- Reflection in logic, functional and object-oriented programming: a short comparative study
- An Introduction to Reflection-Oriented Programming
- Brian Foote's pages on Reflection in Smalltalk
- Java Reflection API Tutorial from Oracle