Reflective programming


In computer science, reflective programming or reflection is the ability of a process 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. As the bulk of programming moved to higher-level compiled languages such as ALGOL, 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'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 and 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 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 that supports 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 are called, various variables such as verb and this 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 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 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 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 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 and invoke its method. For each programming language, normal and reflection-based call sequences are shown.

Common Lisp

The following is an example in Common Lisp using the Lisp Object System">Lisp (programming language)">Lisp Object System:

)
) )
;; Normal, without reflection
)
;; With reflection to look up the class named "foo" and the method
;; named "print-hello" that specializes on "foo".
)))

))

C

Reflection is not possible in C, though parts of reflection can be emulated.

  1. include
  2. include
  3. include
typedef struct Foo;
typedef void ;
// The method: Foo::printHello
void Foo_printHello
// Simulated method table
typedef struct MethodEntry;
MethodEntry fooMethods = ;
// Simulate reflective method lookup
nodiscard
Method findMethodByName
int main

C++

The following is an example in C++.

import std;
using StringView = std::string_view;
template
using Vector = std::vector;
using AccessContext = std::meta::access_context;
using ReflectionException = std::meta::exception;
using Info = std::meta::info;
inline constexpr decltype Filter = std::views::filter;
nodiscard
consteval bool isNonstaticMethod noexcept
nodiscard
consteval Info findMethod
template
constexpr auto createInvokerImpl = -> auto ;
nodiscard
consteval Info createInvoker
class Foo ;
int main

C#

The following is an example in C#:

namespace Wikipedia.Examples;
using System;
using System.Reflection;
class Foo
public class InvokeFooExample

Delphi, Object Pascal

This Delphi and 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 as TRttiInstanceType;
Foo := RttiType.GetMethod.Invoke.AsObject;
try
RttiType.GetMethod.Invoke;
finally
Foo.Free;
end;
end;

eC

The following is an example in eC:

// Without reflection
Foo foo;
foo.hello;
// With reflection
Class fooClass = eSystem_FindClass;
Instance foo = eInstance_New;
Method m = eClass_FindMethod;
);

Go

The following is an example in Go:

import Hello
func main

Java

The following is an example in Java:

package org.wikipedia.example;
import java.lang.reflect.Method;
class Foo
public class InvokeFooExample

Java also provides an internal class in module jdk.unsupported, sun.reflect.Reflection which is used by sun.misc.Unsafe. It contains one method, for obtaining the class making a call at a specified depth. This is now superseded by using the class java.lang.StackWalker.StackFrame and its method.

JavaScript/TypeScript

The following is an example in JavaScript:

import 'reflect-metadata';
// Without reflection
const foo = new Foo;
foo.hello;
// With reflection
const foo = Reflect.construct;
const hello = Reflect.get;
Reflect.apply;
// With eval
eval.hello');

The following is the same example in TypeScript:

import 'reflect-metadata';
// Without reflection
const foo: Foo = new Foo;
foo.hello;
// With reflection
const foo: Foo = Reflect.construct;
const hello: => void = Reflect.get as => void;
Reflect.apply;
// With eval
eval.hello');

Julia

The following is an example in Julia:

julia> struct Point
x::Int
y
end
  1. Inspection with reflection
julia> fieldnames
julia> fieldtypes
julia> p = Point
  1. Access with reflection
julia> getfield

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
- hello;
@end
// Sending "hello" to a Foo instance without reflection.
Foo* obj = Foo alloc] init];
;
// Sending "hello" to a Foo instance with reflection.
id obj = NSClassFromString alloc] init];
;

Perl

The following is an example in Perl:

  1. Without reflection
my $foo = Foo->new;
$foo->hello;
  1. or
Foo->new->hello;
  1. With reflection
my $class = "Foo"
my $constructor = "new";
my $method = "hello";
my $f = $class->$constructor;
$f->$method;
  1. or
$class->$constructor->$method;
  1. 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 = $reflector->newInstance;
$hello = $reflector->getMethod;
$hello->invoke;

Python

The following is an example in Python:

from typing import Any
class Foo:
#...
def print_hello -> None:
print
if __name__ "__main__":
# Without reflection
obj: Foo = Foo
obj.print_hello
# With reflection
obj: Foo = globals
_: Any = getattr
# With eval
eval.print_hello")

R

The following is an example in R:

  1. Without reflection, assuming foo returns an S3-type object that has method "hello"
obj <- foo
hello
  1. With reflection
class_name <- "foo"
generic_having_foo_method <- "hello"
obj <- do.call)
do.call

Ruby

The following is an example in Ruby:

  1. Without reflection
obj = Foo.new
obj.hello
  1. With reflection
obj = Object.const_get.new
obj.send :hello
  1. With eval
eval "Foo.new.hello"

Rust

does not have compile-time reflection in the standard library, but it is possible using some third-party libraries such as "".

use std::any::TypeId;
use bevy_reflect::prelude::*;
use bevy_reflect::;
#
#
struct Foo
impl Foo
#
trait DoFoo
impl DoFoo for Foo
fn main

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
Dim constructors As Introspection.ConstructorInfo = classInfo.GetConstructors
Dim fooInstance As Foo = constructors.Invoke
Dim methods As Introspection.MethodInfo = classInfo.GetMethods
For Each m As Introspection.MethodInfo In methods
If m.Name = "PrintHello" Then
m.Invoke
End If
Next