Reflection (computer science)
Encyclopedia
|
| Tutorials | Encyclopedia | Dictionary | Directory |
|
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 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, where it may not be possible at all. Reflection is also known as self-modifying code, especially at the machine code and assembly language levels.
Reflection-Oriented ProgrammingReflection-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. UsesReflection 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 Reflection is also a key strategy for metaprogramming. ImplementationA 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:
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.. ExamplesActionScriptHere is an equivalent example in ActionScript: 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: 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. Note: The above is not strictly true. Without a reference to the class somewhere in the source, the compiler will simply ignore the class and not include it in the compiled binary. Instantiating a variable will ensure that the compiler includes the class, but it is completely unnecessary and undesirable due to memory issues. Use the following instead: 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 (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 The program loads the assembly dynamically at runtime, and checks that the assembly supports the
//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() { }
}
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();
if (rmAttribute.Length == 1 && parames.Length == 0)
Console.WriteLine("{0}", method.Name);
}
}
}
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 LispHere is an equivalent example in Common Lisp: However, this works only for symbols in topmost lexical environment (or dynamic one). A better example, using CLOS, is: 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. CurlHere is an equivalent example in Curl: || Without reflection
let foo1:Foo = {Foo}
{foo1.hello}
|| Using runtime 'any' calls
let foo2:any = {Foo}
{foo2.hello}
|| Using reflection
let foo3:any = {Foo}
{type-switch {type-of foo3}
case class:ClassType do
{if-non-null method = {class.get-method "hello"} then
{method.invoke foo3}
}
}
All three of these examples instantiate an instance of the 'Foo' class and invoke its 'hello' method. The first, resolves the lookup at compile-time and will generate the most efficient code for invoking the method at runtime. The second, invokes the method through an 'any' variable which will do both the lookup and invocation at runtime, which is much less efficient. The third, uses the reflection interface to lookup the method in the 'Foo' class and invoke it, which is also much less efficient than the first example. Delphi?s dialect of Object PascalAlthough the language itself does not provide explicit support for reflection, this can be done by making use of the runtime type information (RTTI) generated by the compiler, as the following example illustrates. Even more flexible reflections can be achieved by using a runtime compilation engine, like PascalScript. 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']()
IoHere is an equivalent example in Io: // Without reflection hello JavaThe following is an example in Java using the Java package . 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 LuaHere's an equivalent example in Lua: -- Without reflection 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"]() MOOHere is an equivalent example in MOO: "without reflection"; foo:hello(); "with partial reflection";
foo:("hello")();
Objective-CHere is an equivalent example in Objective-C (using Cocoa runtime): PerlHere is an equivalent example in Perl: PHPHere is an equivalent example in PHP. This is the non-reflective way to invoke $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() );
PythonHere is an equivalent example from the Python 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 function and its attendant security risks: REBOLHere is an example in REBOL: ; Without reflection hello This works because the language is fundamentally reflective, processing via symbols, not strings. To illustrate that the above example is reflective (not simply evaluation of a code block) you can write: if 'hello = first [hello] [print "this is true"] RubyHere is an equivalent example in Ruby: SchemeHere is an equivalent example in Scheme: SmalltalkHere is an equivalent example in Smalltalk: 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). Windows PowerShellHere is an equivalent example in Windows PowerShell: # without reflection $foo = new-object Foo $foo.hello() # with reflection $class = 'Foo' $method = 'hello' $object = new-object $class $object.$method.Invoke() See also
References
Further reading
External links
ca:Reflexió (informàtica) de:Reflexion (Programmierung) es:Reflexión (informática) fr:Réflexion (informatique) ko:?? (???) it:Riflessione (informatica) lt:Refleksija (programavimas) nl:Reflectie (informatica) ja:??????? (????) pl:Mechanizm refleksji pt:Reflexão (programação) ru:????????? (????????????????) vi:Reflection (khoa h?c máy tính) zh:?? (?????) Source: Wikipedia | The above article is available under the GNU FDL. | Edit this article
|
|
top
©2008-2009 TutorGig.com. All Rights Reserved. Privacy Statement