Reflection (computer programming)

In computer science, reflection is the ability of a computer program to examine, introspect, and modify its own structure and behavior at runtime.[1]

Historical background

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 into their type systems appeared.

Brian Cantwell Smith's 1982 doctoral dissertation[2][3] introduced the notion of computational reflection in programming languages, and the notion of the meta-circular interpreter as a component of 3-Lisp.

Uses

Reflection can be used for observing and 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 programming 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 be used to adapt a given program to different situations dynamically. Reflection-oriented programming almost always requires additional knowledge, framework, relational mapping, and object relevance in order to take advantage of more generic code execution.

Reflection is often used as part of software testing, such as for the runtime creation/instantiation of mock objects.

Reflection is also a key strategy for metaprogramming.

In some object-oriented programming languages, such as C# and Java, reflection can be used to override member accessibility rules. For example, reflection makes it possible to change the value of a field marked "private" in a third-party library's class.

Implementation

A language supporting reflection provides a number of features available at runtime that would otherwise be difficult 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.

Examples

The following code snippets create an instance foo of class Foo, and invoke its method hello. For each programming language, normal and reflection-based call sequences are shown.

eC

The following is an example in eC:

// without reflection
Foo foo { };
foo.hello();

// with reflection
Class fooClass = eSystem_FindClass(__thisModule, "Foo");
Instance foo = eInstance_New(fooClass);
Method m = eClass_FindMethod(fooClass, "hello", fooClass.module);
((void (*)())(void *)m.function)(foo);

ECMAScript

The following is an example in ECMAScript, and therefore also applies to JavaScript and ActionScript:

// 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()')

// Using ECMAScript 2015's new Reflect class:
Reflect.construct(Foo, [])['hello']()

Go

The following is an example in Go:

import "reflect"

// without reflection
f := Foo{}
f.Hello()

// with reflection
fT := reflect.TypeOf(Foo{})
fV := reflect.New(fT)

m := fV.MethodByName("Hello")
if m.IsValid() {
    m.Call(nil)
}

Java

The following is an example in Java:

// without reflection
Foo foo = new Foo();
foo.hello();

// with reflection
Object foo = Class.forName("complete.classpath.and.Foo").newInstance();
// Alternatively: Object foo = Foo.class.newInstance();
Method m = foo.getClass().getDeclaredMethod("hello", new Class<?>[0]);
m.invoke(foo);

Objective-C

The following is an example in Objective-C—implying either the OpenStep or Foundation Kit framework is used:

// 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)];

Delphi

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;

This is a notable example since Delphi is an unmanaged, fully natively compiled language, unlike most other languages that support reflection. Its language architecture inherits from strongly-typed Pascal, but with significant influence from SmallTalk. Compare with the other examples here, many of which are dynamic or script languages like Perl, Python or PHP, or languages with a runtime like Java or C#.

Perl

The following is an example in Perl:

# without reflection
my $foo = Foo->new;
$foo->hello;

# or
Foo->new->hello;

# with reflection
my $class = "Foo"
my $constructor = "new";
my $method = "hello";

my $f = $class->$constructor;
$f->$method;

# or
$class->$constructor->$method;

# with eval
eval "new Foo->hello;";

PHP

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

Python

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

R

The following is an example in R:

# Without reflection, assuming foo() returns an S3-type object that has method "hello"
obj <- foo()
hello(obj)

# With reflection
the.class <- "foo"
the.method <- "hello"
obj <- do.call(the.class, list())
do.call(the.method, alist(obj))

Ruby

The following is an example in Ruby:

# without reflection
obj = Foo.new
obj.hello

# with reflection
class_name = "Foo"
method_name = :hello
obj = Object.const_get(class_name).new
obj.send method_name

# with eval
eval "Foo.new.hello"

See also

References

Notes

Documents

Further reading

External links

This article is issued from Wikipedia - version of the Tuesday, April 19, 2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.