Reflection (computer science)

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.

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.

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.

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.

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

ActionScript

Here is an equivalent example in ActionScript:// Without reflectionvar foo:Foo = new Foo();foo.hello(); // With reflectionvar 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.

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:Foo;

C#

Here is an equivalent example in C#://Without reflectionFoo foo = new Foo();foo.Hello();

//With reflectionType 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 RecentlyModified 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 attribute. This check is facilitated by using another custom attribute 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(); 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 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")))However, this works only for symbols in topmost lexical environment (or dynamic one).A better example, using CLOS, is:;;Method hello is called on instance of class foo.(hello (make-instance 'foo))

;;or(hello (make-instance (find-class 'foo))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.

Curl

Here 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 Pascal

Although 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.

program Reflections;

{$IFDEF FPC} {$MODE DELPHI}{$ELSE} {$APPTYPE CONSOLE}{$ENDIF}

uses Classes, SysUtils;

type TBase = class(TPersistent) procedure Common; virtual; abstract; end;

{ TDescendentClass

This is a class reference type, which works similar as a metaclass in Cxx). }

TDescendentClass = class of TBase;

TSpecialMethod = procedure (Args: array of const) of object;

TDescendent1 = class(TBase) procedure Common; override; published { Compiler generates RTTI information for methods and fields declared in the PUBLISHED section. } procedure Special(Values: array of const); end;

TDescendent2 = class(TBase) procedure Common; override; end;

{ TDescendent1 }

procedure TDescendent1.Common;begin Writeln('TDescendent1.Common called.');end;

procedure TDescendent1.Special(Values: array of const);var I: Integer;begin { An ARRAY OF CONST is actually an ARRAY OF TVarRec. TVarRec is declared in System.pas represent variants. }

Writeln('TDescendent1.Special called with '); for I := 0 to High(Values) do with Values [I] do begin Write(#9); case VType of vtInteger: Writeln('an integer'); vtBoolean: Writeln('a boolean'); vtChar: Writeln('a char'); vtString, vtAnsiString, vtPChar: Writeln('a string'); vtObject: Writeln('an object'); vtClass: Writeln('a class reference'); else Writeln('something else (VType = ', VType, ')'); end; end;end;

{ TDescendent2 }

procedure TDescendent2.Common;begin Writeln('TDescendent2.Common called.');end;

procedure ClassTest(AClass: TDescendentClass);var Obj: TBase; Special: TSpecialMethod;begin Obj := AClass.Create; try Obj.Common; with TMethod(Special) do begin Code := Obj.MethodAddress('Special'); Data := Obj; end; if Assigned(Special) then Special( [1234, 'str', Char('x'), Obj, AClass, False, 2.2] ); finally Obj.Free; end;end;

var ObjClass: TDescendentClass; I: Integer;

begin RegisterClasses( [TDescendent1, TDescendent2] );

for I := 1 to 2 do begin ObjClass := TDescendentClass(GetClass('TDescendent' + IntToStr(I))); if Assigned(ObjClass) then ClassTest(ObjClass); end;

UnregisterClasses( [TDescendent1, TDescendent2] );end.

Even more flexible reflections can be achieved by using a runtime compilation engine, like [http://www.remobjects.com/product/?id=%7B02A079E7-80AD-4CB4-BCF6-D213F45C4FC4%7D PascalScript] .

ECMAScript (JavaScript)

Here is an equivalent example in ECMAScript:// Without reflectionnew Foo().hello() // With reflection // assuming that Foo resides in thisnew this ['Foo'] () ['hello'] () // or without assumptionnew (eval('Foo'))() ['hello'] ()

Io

Here is an equivalent example in Io:

// Without reflection hello
// With reflection doString("hello")

Java

The following is an example in Java using the Java package Javadoc:SE|package=java.lang.reflect|java/lang/reflect. Consider two pieces of code// Without reflectionFoo foo = new Foo();foo.hello();

// With reflectionClass 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 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.

Lua

Here's an equivalent example in Lua:

"-- Without reflection" hello()
"-- With reflection" loadstring("hello()")()

The function [http://www.lua.org/manual/5.1/manual.html#pdf-loadstring 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 [http://www.lua.org/manual/5.1/manual.html#pdf-_G _G] :

"-- Using the table _G, which holds all global variables" _G ["hello"] ()

MOO

Here is an equivalent example in MOO: "without reflection"; foo:hello(); "with partial reflection"; foo:("hello")();

Objective-C

Here is an equivalent example in Objective-C (using Cocoa runtime):// Without reflection
[Foo alloc] init] hello] ;

// With reflectionClass aClass = NSClassFromString(@"Foo");SEL aSelector = NSSelectorFromString(@"hello"); // or @selector(hello) if the method // name is known at compile time
[aClass alloc] init] performSelector:aSelector] ;

Perl

Here is an equivalent example in Perl:
# without reflectionmy $foo = Foo->new();$foo->hello();

# with reflectionmy $class = "Foo";my $method = "hello";my $object = $class->new();$object->$method();

PHP

Here is an equivalent example in PHP.

This is the non-reflective way to invoke Foo::hello:$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() );

Python

Here 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:>>> # Class definition>>> class Foo(object):... 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>>> instancename = 'foo'>>> methodname = 'Hello'>>> instance = globals() [instancename] >>> method = getattr(instance , methodname)>>> method()Hi>>> # or get a method from class not from object>>> classfoo = type(instance) >>> unboundmethod= getattr(classfoo , methodname)>>> unboundmethod(instance)Hi

REBOL

Here is an example in REBOL:

; Without reflection hello
; With reflection do [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"]

Ruby

Here is an equivalent example in Ruby:
# without reflectionFoo.new.hello

# with reflectionObject.const_get(:Foo).new.send(:hello)

cheme

Here is an equivalent example in Scheme:; Without reflection(hello)

; With reflection(eval '(hello))

; With reflection via string using string I/O ports(eval (read (open-input-string "(hello)")))

malltalk

Here is an equivalent example in Smalltalk:

"Without reflection"Foo new 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:

"With reflection"

x y className methodName

className := 'Foo'.methodName := 'hello'.

x := (Compiler evaluate: className).

(x isKindOf: Class) ifTrue: [ y := x new.

(y respondsTo: methodName asSymbol) ifTrue: [ y perform: methodName asSymbol ]

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."

Windows PowerShell

Here 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()

ee also

*Type introspection
*Self-modifying code
*Programming paradigms
*List of reflective programming languages and platforms

References

* Jonathan M. Sobel and Daniel P. Friedman. [http://www.cs.indiana.edu/~jsobel/rop.html "An Introduction to Reflection-Oriented Programming"] (1996), Indiana University.

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

External links

* [http://citeseer.ist.psu.edu/106401.html Reflection in logic, functional and object-oriented programming: a Short Comparative Study] (Citeseer page).
* [http://www.cs.indiana.edu/~jsobel/rop.html An Introduction to Reflection-Oriented Programming]
* [http://msdn2.microsoft.com/en-us/library/y0114hz2(VS.80).aspx Reflection in C++/CLI for .Net]
* [http://www.garret.ru/~knizhnik/cppreflection/docs/reflect.html Reflection for C++]
* [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1751.html Aspects of Reflection in C++]
* [http://www.codeproject.com/library/libreflection.asp LibReflection:] A reflection library for C++.
* [http://sourceforge.net/projects/cppreflect/ A library to provide full reflection for C++ through template metaprogramming techniques.]
* [http://sourceforge.net/projects/crd A C++ reflection-based data dictionary]
* [http://www.laputan.org/#Reflection Brian Foote's pages on Reflection in Smalltalk]
* [http://java.sun.com/docs/books/tutorial/reflect/index.html Java Reflection Tutorial] from Sun Microsystems
* [http://tutorials.jenkov.com/java-reflection/index.html Java Reflection Tutorial] By Jakob Jenkov


Wikimedia Foundation. 2010.

Игры ⚽ Нужно сделать НИР?

Look at other dictionaries:

  • Reflection (computer programming) — Programming paradigms Agent oriented Automata based Component based Flow based Pipelined Concatenative Concurrent computi …   Wikipedia

  • Namespace (computer science) — For namespaces in general, see Namespace. A namespace (sometimes also called a name scope) is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols (i.e., names). An identifier defined in a… …   Wikipedia

  • Class (computer science) — In object oriented programming, a class is a programming language construct that is used as a blueprint to create objects. This blueprint includes attributes and methods that the created objects all share.More technically, a class is a cohesive… …   Wikipedia

  • Computer security compromised by hardware failure — is a branch of computer security applied to hardware. The objective of computer security includes protection of information and property from theft, corruption, or natural disaster, while allowing the information and property to remain accessible …   Wikipedia

  • Computer data storage — 1 GB of SDRAM mounted in a personal computer. An example of primary storage …   Wikipedia

  • Science in the medieval Islamic world — This article is about the history of science in the Islamic civilization between the 8th and 16th centuries. For information on science in the context of Islam, see Islam and science …   Wikipedia

  • Science fiction film — is a film genre that uses science fiction: speculative, science based depictions of phenomena that are not necessarily accepted by mainstream science, such as extraterrestrial life forms, alien worlds, extrasensory perception, and time travel,… …   Wikipedia

  • Reflection high energy electron diffraction — (RHEED) is a technique used to characterize the surface of crystalline materials. RHEED systems gather information only from the surface layer of the sample, which distinguishes RHEED from other materials characterization methods that rely also… …   Wikipedia

  • science fiction — a form of fiction that draws imaginatively on scientific knowledge and speculation in its plot, setting, theme, etc. [1925 30] * * * Fiction dealing principally with the impact of actual or imagined science on society or individuals, or more… …   Universalium

  • Science-Fiction-Autor — Dies ist eine Liste bedeutender Autoren von Science Fiction. A Autor Leben Sprache Werk Kōbō Abe 1924–1993 japanisch Die vierte Zwischeneiszeit Forrest J. Ackerman 1916−2008 englisch Science Fiction (Herausgeber) …   Deutsch Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”