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.
At the lowest level, machine code can be treated reflectively because the distinction between instruction and data becomes just a matter of how the information is treated by the computer. Normally, \'instructions\' are \'executed\' and \'data\' is \'processed\', however, the program can also treat instructions as data and therefore make reflective modifications. Reflection is most common in high-level virtual machine programming languages like Smalltalk, and less common in lower-level programming languages like C.
Common types of reflection are runtime and dynamic, but some programming languages support compile time or static reflection.
Reflective programming is a programming paradigm, used as an extension to the object-oriented programming paradigm, to add self-optimization to application programs, and to improve their flexibility. In this paradigm, computation is equated not with a program but with execution of a program. Other imperative approaches, such as procedural or object-oriented paradigm, specify that there is a pre-determined sequence of operations (function or method calls), that modify any data or object they are given. In contrast, the reflective paradigm states that the sequence of operations won\'t be decided at compile time, rather the flow of sequence will be decided dynamically, based on the data that need to be operated upon, and what operation needs to be performed. The program will only code the sequence of how to identify the data and how to decide which operation to perform.
Any computation can be classified as either of two:
Atomic – The operation completes in a single logical step, such as addition of two numbers.
Compound – Defined as a sequence of multiple atomic operations.
A compound statement, in classic procedural or object-oriented programming, loses its structure once it is compiled. The reflective paradigm introduces the concept of meta-information, which keeps knowledge of this structure. Meta-information stores information such as the name of the contained methods, name of the class, name of parent classes, or even what the compound statement is supposed to do. This is achieved by keeping information of the change of states that the statement causes the data to go through. So, when a datum (object) is encountered, it can be reflected to find out the operations that it supports, and the one that causes the required state transition can be chosen at run-time, without the need to specify it in code.
Uses
Reflection can be used for self-optimization or self-modification of a program. A reflective sub-component of a program will monitor the execution of a program and will optimize or modify itself according to the function the program is solving. This is done by modifying the program\'s own memory area, where the code is stored.
Reflection can also be used to adapt a given system dynamically to different situations. Consider, for example, an application that uses some class X to communicate with some service. Now suppose it needed to communicate with a different service, via a different class Y, which has different method names. If the method names were hard coded into the application, it would need to be rewritten, but if it used reflection this could be avoided. Using reflection, the application would have a knowledge about the methods in class X. And class X could be designed to provide information regarding which method is being used for what purpose. The application, depending on what it has to do, would select the required method and use it. Now, when the different service is being used, via class Y, the application would search the methods in the new class to find the required methods and use them. No modification of the code is necessary. Even the class name need not be hard coded, rather it can be stored in a configuration file, it will be correctly searched for and loaded at run time.
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.
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..
Examples
Java
The following is an example in Java using the Java packagejava.lang.reflect. Consider two pieces of code
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Method method = cls.getMethod("hello", null);
method.invoke(cls.newInstance(), 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. 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.
Here is an equivalent example from the Python shell with two ways of doing reflection:
>>> # Class definition
>>> class Foo():
... 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
>>> instance = \'foo\'
>>> method = \'Hello\'
>>> getattr(globals()[instance], method)()
Hi
Objective-C
Here is an equivalent example in Objective-C (using Cocoa runtime):
// Without reflection
[[[Foo alloc] init] hello];
// With reflection
Class aClass = NSClassFromString(@"Foo");
SEL aSelector = NSSelectorFromString(@"hello"); // or @selector(hello) if the method
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.
ActionScript
Here is an equivalent example in ActionScript:
// Without reflection
var foo:Foo = new Foo();
foo.hello();
// With reflection
var ClassReference:Class = flash.utils.getDefinitionByName("Foo") as Class;
var instance:Object = new ClassReference();
instance.hello();
Even with an import statement on “Foo”, the method call to “getDefinitionByName” will break without an internal reference to the class. This is because runtime compilation of source is not currently supported. To get around this, you have to have at least one instantiation of the class type in your code for the above to work. So in your class definition you declare a variable of the custom type you want to use:
var customType : Foo;
So for the idea of dynamically creating a set of views in Flex 2 using these methods in conjunction with an xml file that may hold the names of the views you want to use, in order for that to work, you will have to instantiate a variable of each type of view that you want to utilize.
ECMAScript (JavaScript)
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\']()
; Without reflection
(hello)
; With reflection
(eval \'(hello))
; With reflection via string using string I/O ports
(eval (read (open-input-string "(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:
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."
-- Without reflectionhello()
-- With reflectionloadstring("hello()")()
The function loadstring compiles the chunk and returns it as a parameterless function.
If hello is a global function, it can be accessed by using the table _G:
-- Using the table _G, which holds all global variables
_G["hello"]()
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);
The following example, written in C#, demonstrates the use of advanced features of reflection. It loads an assembly (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 attributeRecentlyModified 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. This check is facilitated by using another custom attrubute 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
{
public RecentlyModifiedAttribute() { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)]
class SupportsRecentlyModifiedAttribute : Attribute
{
public SupportsRecentlyModifiedAttribute() { }
}
Implementation of the method filter
static void Main(string[] args)
{
//Load the assembly dynamically and make sure it supports the Recently Modified Attribute
Assembly loadedAssembly = Assembly.LoadAssembly(Console.ReadLine());
if (Attribute.GetCustomAttribute(
loadedAssembly, typeof(SupportsRecentlyModifiedAttribute)) != null)
//For each class in the assembly, get all the methods. Iterate through the methods
//and find the ones that have both the RecentlyModified attribute set as well as do
//not require any arguments.
foreach (Type t in loadedAssembly.GetTypes())
{
if (t.IsClass)
foreach (MethodInfo method in t.GetMethods())
{
//Try to retrieve the RecentlyModified attribute
object[] rmAttribute = method.GetCustomAttributes(
typeof(RecentlyModifiedAttribute), false);
//Try to retrieve the parameters
ParameterInfo[] parames = method.GetParameters();