Reflection (computer programming)
- Concurrent computing
- Relativistic programming
- Declarative (contrast: Imperative)
- Function-level (contrast: Value-level)
- Imperative (contrast: Declarative)
- Non-structured (contrast: Structured)
- Parallel computing
- Programming in the large / small
- Structured (contrast: Non-structured)
- Value-level (contrast: Function-level)
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, C, ML or Haskell.
- 1 Historical background
- 2 Uses
- 3 Implementation
- 4 Examples
- 5 See also
- 6 References
- 7 Further reading
- 8 External links
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
Yinterchangeably to perform similar operations. Without reflection-oriented programming, the application might be hard-coded to call method names of 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
Ywithout 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.
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.
The following examples show an instance
fooof a class
Foobeing created, and a method
Hello) of the instance being called. For each language, two versions are shown; the first being a call sequence without reflection and the second using reflection to access the class and the method.
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);
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)
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)
// Without reflection new Foo().hello() // With reflection // assuming that Foo resides in this new this['Foo']()['hello']() // or without assumption new (eval('Foo'))()['hello']()
// Without reflection new Foo().hello(); // With reflection Class<?> cls = Class.forName("Foo"); cls.getMethod("hello").invoke(cls.newInstance());
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 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.
The following is an example in Lua
-- without reflection Foo.hello() -- with reflection _G['Foo']['hello']()
The following is an example in Objective-C
// Without reflection Foo *foo = [[Foo alloc] init]; [foo hello]; // With reflection Class cls = NSClassFromString(@"Foo"); id foo = [[cls alloc] init]; SEL selector = NSSelectorFromString(@"hello"); [foo performSelector:selector withObject:nil];
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();
Here is an equivalent 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();
Here is an equivalent example in Python:
# without reflection Foo().hello() # with reflection getattr(globals()['Foo'](), 'hello')()
Here is an equivalent example in Ruby:
# without reflection Foo.new.hello # with reflection Object.const_get(:Foo).send(:new).send(:hello)
Here is an equivalent example in e:
# without reflection var foo : Foo = new; foo.hello(); # with reflection rf_manager.get_type_by_name(foo).get_method("hello").invoke(foo);
Here is an equivalent example in Smalltalk:
"Without reflection" Foo new hello "With reflection" ((Smalltalk at: #Foo) perform: #new) perform: #hello
Here is an equivalent example in Io:
Foo := Object clone do( hello := method( "Hello" println ) ) #Without reflection Foo hello #With reflection getSlot("Foo") getSlot("hello") call
Here is an equivalent example in Actionscript:
//Without reflection var foo:Foo = new Foo(); foo.hello(); //With reflection var cls:Object = getDefinitionByName("Foo"); var foo:Object = new cls(); foo["hello"]();
- Type introspection
- Self-modifying code
- Programming paradigms
- List of reflective programming languages and platforms
- ^ 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 Tutorial from Sun Microsystems
Wikimedia Foundation. 2010.
Look at other dictionaries:
Reflection (computer science) — In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior. The programming paradigm driven by reflection is called reflective programming .In most modern computer… … Wikipedia
Class (computer programming) — 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 … Wikipedia
Reflection — or reflexion may refer to:Computers* in computer graphics, the techniques for simulating optical Reflection. * Reflection, a programming language feature for metaprogramming * Reflection , a piece of installation art by Shane Cooper also called… … Wikipedia
computer graphics — 1. pictorial computer output produced on a display screen, plotter, or printer. 2. the study of the techniques used to produce such output. [1970 75] * * * Use of computers to produce visual images, or the images so produced. Creating computer… … Universalium
List of programming languages by category — Programming language lists Alphabetical Categorical Chronological Generational This is a list of programming languages grouped by category. Some languages are listed in multiple categories. Contents … Wikipedia
Comparison of programming languages (object-oriented programming) — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations … Wikipedia
Comparison of programming languages (basic instructions) — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations … Wikipedia
Extensible programming — is a term used in computer science to describe a style of computer programming that focuses on mechanisms to extend the programming language, compiler and runtime environment. Extensible programming languages, supporting this style of programming … Wikipedia
Python (programming language) — infobox programming language name = Python paradigm = multi paradigm: object oriented, imperative, functional year = 1991 designer = Guido van Rossum developer = Python Software Foundation latest release version = 2.6 latest release date =… … Wikipedia
Home computer — A home computer was a class of personal computer entering the market in 1977 and becoming common during the 1980s. [ [http://www.homecomputer.de/ Home of the home computer] website] They were marketed to consumers as accessible personal computers … Wikipedia