In
computer science, reflective programming or reflection is the ability of a
process to examine,
introspect
Introspection is the examination of one's own conscious thoughts and feelings. In psychology, the process of introspection relies on the observation of one's mental state, while in a spiritual context it may refer to the examination of one's sou ...
, and modify its own structure and behavior.
Historical background
The earliest computers were programmed in their native
assembly language
In computer programming, assembly language (or assembler language, or symbolic machine code), often referred to simply as Assembly and commonly abbreviated as ASM or asm, is any low-level programming language with a very strong correspondence be ...
s, which were inherently reflective, as these original architectures could be programmed by defining instructions as data and using
self-modifying code. As the bulk of programming moved to higher-level
compiled languages
A compiled language is a programming language whose implementations are typically compilers (translators that generate machine code from source code), and not interpreters (step-by-step executors of source code, where no pre-runtime translation t ...
such as
Algol,
Cobol
COBOL (; an acronym for "common business-oriented language") is a compiled English-like computer programming language designed for business use. It is an imperative, procedural and, since 2002, object-oriented language. COBOL is primarily us ...
,
Fortran,
Pascal
Pascal, Pascal's or PASCAL may refer to:
People and fictional characters
* Pascal (given name), including a list of people with the name
* Pascal (surname), including a list of people and fictional characters with the name
** Blaise Pascal, Fren ...
, and
C, this reflective ability largely disappeared until new programming languages with reflection built into their type systems appeared.
Brian Cantwell Smith's 1982 doctoral dissertation introduced the notion of computational reflection in procedural
programming languages and the notion of the
meta-circular interpreter as a component of
3-Lisp.
Uses
Reflection helps programmers make generic software libraries to display data, process different formats of data, perform
serialization
In computing, serialization (or serialisation) is the process of translating a data structure or object state into a format that can be stored (e.g. files in secondary storage devices, data buffers in primary storage devices) or transmitted (e ...
or deserialization of data for communication, or do bundling and unbundling of data for containers or bursts of communication.
Effective use of reflection almost always requires a plan: A design framework, encoding description, object library, a map of a database or entity relations.
Reflection makes a language more suited to network-oriented code. For example, it assists languages such as
Java to operate well in networks by enabling libraries for serialization, bundling and varying data formats. Languages without reflection such as
C are required to use auxiliary compilers for tasks like
Abstract Syntax Notation to produce code for serialization and bundling.
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 of 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 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 bypass
member accessibility rules. For C#-properties this can be achieved by writing directly onto the (usually invisible) backing field of a non-public property. It is also possible to find non-public methods of classes and types and manually invoke them. This works for project-internal files as well as external libraries such as
.NET's assemblies and Java's archives.
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:
* Discover and modify
source-code constructions (such as code blocks,
classes, methods, protocols, etc.) as
first-class objects at
runtime.
* Convert a
string
String or strings may refer to:
*String (structure), a long flexible structure made from threads twisted together, which is used to tie, bind, or hang other objects
Arts, entertainment, and media Films
* ''Strings'' (1991 film), a Canadian anim ...
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
Bytecode (also called portable code or p-code) is a form of instruction set designed for efficient execution by a software interpreter. Unlike human-readable source code, bytecodes are compact numeric codes, constants, and references (norma ...
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
Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
, the runtime environment must include a compiler or an interpreter.
Reflection can be implemented for languages without built-in reflection by using a
program transformation system to define automated source-code changes.
Security considerations
Reflection may allow a user to create unexpected
control flow paths through an application, potentially bypassing security measures. This may be exploited by attackers. Historical
vulnerabilities in Java caused by unsafe reflection allowed code retrieved from potentially untrusted remote machines to break out of the Java
sandbox
A sandbox is a sandpit, a wide, shallow playground construction to hold sand, often made of wood or plastic.
Sandbox or Sand box may also refer to:
Arts, entertainment, and media
* Sandbox (band), a Canadian rock music group
* Sandbox ( ...
security mechanism. A large scale study of 120 Java vulnerabilities in 2013 concluded that unsafe reflection is the most common vulnerability in Java, though not the most exploited.
Examples
The following code snippets create an
instance
Instantiation or instance may refer to:
Philosophy
* A modern concept similar to ''participation'' in classical Platonism; see the Theory of Forms
* The instantiation principle, the idea that in order for a property to exist, it must be had by ...
of
class and invoke its
method . For each
programming language, normal and reflection-based call sequences are shown.
C#
The following is an example in
C#:
// Without reflection
Foo foo = new Foo();
foo.PrintHello();
// With reflection
Object foo = Activator.CreateInstance("complete.classpath.and.Foo");
MethodInfo method = foo.GetType().GetMethod("PrintHello");
method.Invoke(foo, null);
Delphi / Object Pascal
This
Delphi
Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient classical world. The oracle ...
/
Object Pascal example assumes that a class has been declared in a unit called :
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;
eC
The following is an example in eC (programming language), 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);
Go
The following is an example in
Go (programming language), 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()
Java
The following is an example in
Java:
import java.lang.reflect.Method;
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
try catch (ReflectiveOperationException ignored)
JavaScript
The following is an example in
JavaScript:
// Without reflection
const foo = new Foo()
foo.hello()
// With reflection
const foo = Reflect.construct(Foo)
const hello = Reflect.get(foo, 'hello')
Reflect.apply(hello, foo, [])
// With eval
eval('new Foo().hello()')
Julia
The following is an example in Julia (programming language):
julia> struct Point
x::Int
y
end
# Inspection with reflection
julia> fieldnames(Point)
(:x, :y)
julia> fieldtypes(Point)
(Int64, Any)
julia> p = Point(3,4)
# Access with reflection
julia> getfield(p, :x)
3
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
The terms foobar (), foo, bar, baz, and others are used as metasyntactic variables and placeholder names in computer programming or computer-related documentation. - Etymology of "Foo" They have been used to name entities such as variables, fun ...
init];
bj hello
BJ or B. J. may refer to:
Businesses and organizations
* BJ Services Company, an oil and gas equipment and services company that is now a subsidiary of Baker Hughes
* BJ's Restaurant & Brewery, an American restaurant chain
* BJ's Wholesale Club, ...
// Sending "hello" to a Foo instance with reflection.
id obj = NSClassFromString(@"Foo") allocinit];
bj performSelector: @selector(hello)
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, using Reflections API
$reflector = new ReflectionClass('Foo');
$foo = $reflector->newInstance();
$hello = $reflector->getMethod('hello');
$hello->invoke($foo);
Python
The following is an example in
Python:
# Without reflection
obj = Foo()
obj.hello()
# With reflection
obj = globals() Foo")
getattr(obj, "hello")()
# 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
class_name <- "foo"
generic_having_foo_method <- "hello"
obj <- do.call(class_name, list())
do.call(generic_having_foo_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"
Xojo
The following is an example using
Xojo:
' Without reflection
Dim fooInstance As New Foo
fooInstance.PrintHello
' With reflection
Dim classInfo As Introspection.Typeinfo = GetTypeInfo(Foo)
Dim constructors() As Introspection.ConstructorInfo = classInfo.GetConstructors
Dim fooInstance As Foo = constructors(0).Invoke
Dim methods() As Introspection.MethodInfo = classInfo.GetMethods
For Each m As Introspection.MethodInfo In methods
If m.Name = "PrintHello" Then
m.Invoke(fooInstance)
End If
Next
See also
*
List of reflective programming languages and platforms
Programming languages and computing platforms that typically support reflective programming (reflection) include dynamically typed languages such as Smalltalk, Perl, PHP, Python, VBScript, and JavaScript. Also the .NET languages are supported an ...
*
Mirror (programming) In computer programming, a mirror is a reflection mechanism that is completely decoupled from the object whose structure is being introspected. This is as opposed to traditional reflection, for example in Java, where one introspects an object using ...
*
Programming paradigms
*
Self-hosting (compilers)
*
Self-modifying code
*
Type introspection
*
typeof
References
Citations
Sources
* Jonathan M. Sobel and Daniel P. Friedman
''An Introduction to Reflection-Oriented Programming''(1996),
Indiana University.
Anti-Reflection technique using C# and C++/CLI wrapper to prevent code thief
Further reading
* Ira R. Forman and Nate Forman, ''Java Reflection in Action'' (2005),
* Ira R. Forman and Scott Danforth, ''Putting Metaclasses to Work'' (1999),
External links
Reflection in logic, functional and object-oriented programming: a short comparative studyBrian Foote's pages on Reflection in Smalltalkfrom Oracle
{{DEFAULTSORT:Reflection (Computer Programming)
Programming constructs
Articles with example Python (programming language) code