In
computer science
Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to practical disciplines (includi ...
, reflective programming or reflection is the ability of a
process
A process is a series or set of activities that interact to produce a result; it may occur once-only or be recurrent or periodic.
Things called a process include:
Business and management
*Business process, activities that produce a specific se ...
to examine,
introspect, and modify its own structure and behavior.
Historical background
The earliest computers were programmed in their native
assembly languages, which were inherently reflective, as these original architectures could be programmed by defining instructions as data and using
self-modifying code
In computer science, self-modifying code (SMC) is code that alters its own instructions while it is executing – usually to reduce the instruction path length and improve performance or simply to reduce otherwise repetitively similar 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 translati ...
such as
Algol
ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
,
Cobol,
Fortran,
Pascal, and
C, this reflective ability largely disappeared until new programming languages with reflection built into their type systems appeared.
Brian Cantwell Smith
Brian Cantwell Smith is a philosopher and cognitive scientist working in the fields of cognitive science, computer science, information studies, and philosophy, especially ontology.
His research has focused on the foundations and philosophy o ...
's 1982 doctoral dissertation introduced the notion of computational reflection in procedural
programming languages
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
and the notion of the
meta-circular interpreter In computing, a meta-circular evaluator (MCE) or meta-circular interpreter (MCI) is an interpreter which defines each feature of the interpreted language using a similar facility of the interpreter's host language. For example, interpreting a lambd ...
as a component of
3-Lisp.
Uses
Reflection helps programmers make generic software libraries to display data, process different formats of data, perform
serialization 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
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
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
Abstract Syntax Notation One (ASN.1) is a standard interface description language for defining data structures that can be serialized and deserialized in a cross-platform way. It is broadly used in telecommunications and computer networking, and ...
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
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
languages such as
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
, reflection allows ''inspection'' of classes, interfaces, fields and methods at runtime without knowing the names of the interfaces, fields, methods at
compile time
In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled.
The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concep ...
. It also allows ''instantiation'' of new objects and ''invocation'' of methods.
Reflection is often used as part of
software testing
Software testing is the act of examining the artifacts and the behavior of the software under test by validation and verification. Software testing can also provide an objective, independent view of the software to allow the business to apprecia ...
, such as for the runtime creation/instantiation of
mock object
In object-oriented programming, mock objects are simulated objects that mimic the behaviour of real objects in controlled ways, most often as part of a software testing initiative. A programmer typically creates a mock object to test the behaviou ...
s.
Reflection is also a key strategy for
metaprogramming
Metaprogramming is a programming technique in which computer programs have the ability to treat other programs as their data. It means that a program can be designed to read, generate, analyze or transform other programs, and even modify itself ...
.
In some object-oriented programming languages such as
C# and
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
, reflection can be used to bypass
member accessibility
In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods). In many languages, the class n ...
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
In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the w ...
constructions (such as code blocks,
classes, methods, protocols, etc.) as
first-class object
In programming language design, a first-class citizen (also type, object, entity, or value) in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include ...
s 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.
* 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
A MOO ("MUD, object-oriented") is a text-based online virtual reality system to which multiple users (players) are connected at the same time.
The term MOO is used in two distinct, but related, senses. One is to refer to those programs descend ...
, 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
Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXT ...
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 without built-in reflection by using a
program transformation
A program transformation is any operation that takes a computer program and generates another program. In many cases the transformed program is required to be semantically equivalent to the original, relative to a particular formal semantics and ...
system to define automated source-code changes.
Security considerations
Reflection may allow a user to create unexpected
control flow
In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''im ...
paths through an application, potentially bypassing security measures. This may be exploited by attackers. Historical
vulnerabilities
Vulnerability refers to "the quality or state of being exposed to the possibility of being attacked or harmed, either physically or emotionally."
A window of vulnerability (WOV) is a time frame within which defensive measures are diminished, com ...
in Java caused by unsafe reflection allowed code retrieved from potentially untrusted remote machines to break out of the Java
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 of
class
Class or The Class may refer to:
Common uses not otherwise categorized
* Class (biology), a taxonomic rank
* Class (knowledge representation), a collection of individuals or objects
* Class (philosophy), an analytical concept used differentl ...
and invoke its
method
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
. For each
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
, 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/
Object Pascal
Object Pascal is an extension to the programming language Pascal that provides object-oriented programming (OOP) features such as classes and methods.
The language was originally developed by Apple Computer as ''Clascal'' for the Lisa Worksh ...
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
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
:
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
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
:
// 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
Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXT ...
, implying either the
OpenStep
OpenStep is a defunct object-oriented application programming interface (API) specification for a legacy object-oriented operating system, with the basic goal of offering a NeXTSTEP-like environment on non-NeXTSTEP operating systems. OpenStep wa ...
or
Foundation Kit
The Foundation Kit, or just Foundation for short, is an Objective-C framework in the OpenStep specification. It provides basic classes such as wrapper classes and data structure classes. This framework uses the prefix NS (for NeXTSTEP). It is a ...
framework is used:
// Foo class.
@interface Foo : NSObject
- (void)hello;
@end
// Sending "hello" to a Foo instance without reflection.
Foo *obj = Foo allocinit];
bj hello
// 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
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
:
# 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
PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
:
// 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
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
:
# 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
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called ...
:
# 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
The Xojo programming environment and programming language is developed and commercially marketed by Xojo, Inc. of Austin, Texas for software development targeting macOS, Microsoft Windows, Linux, iOS, the Web and Raspberry Pi. Xojo uses a propri ...
:
' 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
*
Mirror (programming)
*
Programming paradigm
Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms.
Some paradigms are concerned mainly with implications for the execution model of the language, suc ...
s
*
Self-hosting (compilers)
In computer programming, self-hosting is the use of a program as part of the toolchain or operating system that produces new versions of that same program—for example, a compiler that can compile its own source code. Self-hosting software is co ...
*
Self-modifying code
In computer science, self-modifying code (SMC) is code that alters its own instructions while it is executing – usually to reduce the instruction path length and improve performance or simply to reduce otherwise repetitively similar code, ...
*
Type introspection
In computing, type introspection is the ability of a program to ''examine'' the type or properties of an object
at runtime.
Some programming languages possess this capability.
Introspection should not be confused with reflection, which goes a st ...
*
typeof
typeof, alternately also typeOf, and TypeOf, is an operator provided by several programming languages to determine the data type of a variable. This is useful when constructing programs that must accept multiple types of data without explicitly s ...
References
Citations
Sources
* Jonathan M. Sobel and Daniel P. Friedman
''An Introduction to Reflection-Oriented Programming''(1996),
Indiana University
Indiana University (IU) is a system of public universities in the U.S. state of Indiana.
Campuses
Indiana University has two core campuses, five regional campuses, and two regional centers under the administration of IUPUI.
*Indiana Universi ...
.
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