# Reflective programming

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/Reflective_programming
> Markdown URL: https://mediated.wiki/source/Reflective_programming.md
> Source: https://en.wikipedia.org/wiki/Reflective_programming
> Source revision: 1356393088
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

{{Short description|Ability of a process to examine and modify itself}}
{{distinguish|Reflection (computer graphics)}}

In [computer science](/source/computer_science), '''reflective programming''' or '''reflection''' is the ability of a [process](/source/Process_(computing)) to examine, [introspect](/source/Introspection_(computer_science)), and modify its own structure and behavior.<ref>{{Citation | title = A Tutorial on Behavioral Reflection and its Implementation by Jacques Malenfant et al. | publisher = unknown | url = http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/malenfant.pdf | access-date = 23 June 2019 | archive-url = https://web.archive.org/web/20170821214626/http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/malenfant.pdf | archive-date = 21 August 2017 }}</ref>

==Historical background==
The earliest computers were programmed in their native [assembly language](/source/assembly_language)s, which were inherently reflective, as these original architectures could be programmed by defining instructions as data and using [self-modifying code](/source/self-modifying_code). As the bulk of programming moved to higher-level [compiled languages](/source/compiled_languages) such as [ALGOL](/source/ALGOL), [COBOL](/source/COBOL), [Fortran](/source/Fortran), [Pascal](/source/Pascal_(programming_language)), and [C](/source/C_(programming_language)), this reflective ability largely disappeared until new programming languages with reflection built into their type systems appeared.{{Citation needed|date=July 2015}}

[Brian Cantwell Smith](/source/Brian_Cantwell_Smith)'s 1982 doctoral dissertation introduced the notion of computational reflection in [procedural](/source/Procedural_programming) [programming languages](/source/programming_languages) and the notion of the [meta-circular interpreter](/source/meta-circular_interpreter) as a component of 3-[Lisp](/source/Lisp_(programming_language)).<ref>Brian Cantwell Smith, [http://hdl.handle.net/1721.1/15961 Procedural Reflection in Programming Languages], Department of Electrical Engineering and Computer Science, Massachusetts Institute of Technology, PhD dissertation, 1982.</ref><ref>Brian C. Smith. [http://publications.csail.mit.edu/lcs/specpub.php?id=840 Reflection and semantics in a procedural language] {{Webarchive|url=https://web.archive.org/web/20151213034343/http://publications.csail.mit.edu/lcs/specpub.php?id=840 |date=2015-12-13 }}. Technical Report MIT-LCS-TR-272, Massachusetts Institute of Technology, Cambridge, Massachusetts, January 1982.</ref>

==Uses==
Reflection helps programmers make generic software libraries to display data, process different formats of data, perform [serialization](/source/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](/source/Java_(programming_language)) to operate well in networks by enabling libraries for serialization, bundling and varying data formats. Languages without reflection such as [C](/source/C_(programming_language)) are required to use auxiliary compilers for tasks like [Abstract Syntax Notation](/source/Abstract_Syntax_Notation) to produce code for serialization and bundling.

Reflection can be used for observing and modifying program execution at [runtime](/source/Runtime_(program_lifecycle_phase)). 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](/source/object-oriented_programming) languages such as [Java](/source/Java_(programming_language)), reflection allows ''inspection'' of classes, interfaces, fields and methods at runtime without knowing the names of the interfaces, fields, methods at [compile time](/source/compile_time). It also allows ''[instantiation](/source/Instantiation_(computing))'' of new objects and ''invocation'' of methods.

Reflection is often used as part of [software testing](/source/software_testing), such as for the runtime creation/instantiation of [mock object](/source/mock_object)s.

Reflection is also a key strategy for [metaprogramming](/source/metaprogramming).

In some object-oriented programming languages such as [C#](/source/C_Sharp_(programming_language)) and [Java](/source/Java_(programming_language)), reflection can be used to bypass [member accessibility](/source/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](/source/.NET_Framework)'s assemblies and Java's archives.

==Implementation==
{{Unreferenced section|date=January 2008}}
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:
* Discover and modify [source-code](/source/Source_code) constructions (such as code blocks, [classes](/source/Class_(computer_science)), methods, protocols, etc.) as [first-class object](/source/first-class_object)s at [runtime](/source/Runtime_(program_lifecycle_phase)).
* Convert a [string](/source/string_(computer_science)) matching the symbolic name of a class or function into a reference to or invocation of that class or function.<ref>{{Cite web |title=CLHS: Function INTERN |url=http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun_intern.html |access-date=2026-03-27 |website=www.ai.mit.edu}}</ref>
* Evaluate a string as if it were a source-code statement at runtime.<ref>{{Cite web |title=Built-in Functions |url=https://docs.python.org/3/library/functions.html |access-date=2026-03-27 |website=Python documentation |language=en}}</ref><ref>{{Cite web |date=2026-01-21 |title=eval() - JavaScript {{!}} MDN |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval |access-date=2026-03-27 |website=MDN Web Docs |language=en-US}}</ref>
* Create a new [interpreter](/source/Interpreter_(computing)) for the language's [bytecode](/source/bytecode) to give a new meaning or purpose for a programming construct.

These features can be implemented in different ways. In [MOO](/source/MOO_(programming_language)), reflection forms a natural part of everyday programming idiom. When verbs (methods) are called, various variables such as <code>verb</code> (the name of the verb being called) and <code>this</code> (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 <code>callers()</code> is a list of the methods by which the current verb was eventually called, performing tests on <code>callers()[0]</code> (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](/source/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](/source/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](/source/program_transformation) system to define automated source-code changes.

==Security considerations==

Reflection may allow a user to create unexpected [control flow](/source/control_flow) paths through an application, potentially bypassing security measures. This may be exploited by attackers.<ref>{{cite report |first1=Paulo |last1=Barros |first2=René |last2=Just |first3=Suzanne |last3=Millstein |first4=Paul |last4=Vines |first5=Werner |last5=Dietl |first6=Marcelo |last6=d'Amorim |first7=Michael D. |last7=Ernst |date=August 2015 |title=Static Analysis of Implicit Control Flow: Resolving Java Reflection and Android Intents |url=https://homes.cs.washington.edu/~mernst/pubs/implicit-control-flow-tr150801.pdf |publisher=University of Washington |id=UW-CSE-15-08-01 |access-date=October 7, 2021 }}</ref> Historical [vulnerabilities](/source/Vulnerability_(computing)) in Java caused by unsafe reflection allowed code retrieved from potentially untrusted remote machines to break out of the Java [sandbox](/source/Sandbox_(computer_security)) 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.<ref>{{cite magazine |author=Eauvidoum, Ieu |author2=disk noise |date=October 5, 2021 |title=Twenty years of Escaping the Java Sandbox |url=http://phrack.org/issues/70/7.html#article |magazine=[Phrack](/source/Phrack) |volume=10 |issue=46 |access-date=October 7, 2021}}</ref>

==Runtime Performance==

[Reflective programming](/source/Reflective_programming) commonly introduces a non-negligible [runtime performance](/source/runtime_performance) overhead. Because reflective operations are resolved dynamically at execution time, many [Java](/source/Java_(programming_language)) compiler and [JVM](/source/JVM) optimizations—such as [method inlining](/source/method_inlining), [static binding](/source/static_binding), and aggressive just-in-time specialization—cannot be fully applied. As a consequence, reflective calls are typically slower than their statically resolved counterparts. [Microbenchmark](/source/Microbenchmark) and application-level studies on [Java](/source/Java_(programming_language)) have shown that reflective operations can incur substantial runtime overhead, especially for [method invocation](/source/method_invocation) and dynamic object creation, with slowdowns ranging from around 20–40% in moderate cases to more than 300× in heavily reflective dispatch scenarios.<ref name="Garcia2026">Miguel Garcia, Francisco Ortin. [https://doi.org/10.1145/3815583 Characterizing the Usage and Performance Impact of Java Reflection: An Empirical Study], ACM Transactions on Software Engineering and Methodology, 2026.</ref> In sequential applications, [reflection](/source/Reflective_programming) can significantly increase [execution time](/source/execution_time) and memory consumption when used in performance-critical code paths. In [multithreaded applications](/source/Thread_(computing)), reflective implementations generally preserve [scalability](/source/scalability), but still exhibit noticeably higher absolute execution times—commonly between 1.5x and 10× slower—than equivalent non-reflective code.<ref name="Garcia2026" />

==Examples==
The following code snippets create an [instance](/source/instance_(computer_science)) {{code|foo}} of [class](/source/class_(computer_science)) {{code|Foo}} and invoke its [method](/source/method_(computer_science)) {{code|PrintHello}}. For each [programming language](/source/programming_language), normal and reflection-based call sequences are shown.

=== Common Lisp ===
The following is an example in [Common Lisp](/source/Common_Lisp) using the [Common Lisp Object System](/source/Common_Lisp_Object_System):

<syntaxhighlight lang="lisp">
(defclass foo () ())
(defmethod print-hello ((f foo)) (format T "Hello from ~S~%" f))

;; Normal, without reflection
(let ((foo (make-instance 'foo)))
  (print-hello foo))

;; With reflection to look up the class named "foo" and the method
;; named "print-hello" that specializes on "foo".
(let* ((foo-class (find-class (read-from-string "foo")))
       (print-hello-method (find-method (symbol-function (read-from-string "print-hello"))
                                        nil (list foo-class))))
  (funcall (sb-mop:method-generic-function print-hello-method)
           (make-instance foo-class)))
</syntaxhighlight>

=== C ===
Reflection is not possible in [C](/source/C_(programming_language)), though parts of reflection can be emulated.

<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    // ...
} Foo;

typedef void (*Method)(void*);

// The method: Foo::printHello
void Foo_printHello([maybe_unused](/source/maybe_unused) void* this) {
    (void)this; // Instance ignored for a static method
    printf("Hello, world!\n");
}

// Simulated method table
typedef struct {
    const char* name;
    Method fn;
} MethodEntry;

MethodEntry fooMethods[] = {
    { "printHello", Foo_printHello },
    { NULL, NULL } // Sentinel to mark end
};

// Simulate reflective method lookup
[nodiscard](/source/nodiscard)
Method findMethodByName(const char* name) {
    for (size_t i = 0; fooMethods[i].name; i++) {
        if (strcmp(fooMethods[i].name, name) == 0) {
            return fooMethods[i].fn;
        }
    }
    return NULL;
}

int main() {
    // Without reflection
    Foo fooInstance;
    Foo_printHello(&fooInstance);

    // With emulated reflection
    Foo* reflectedFoo = (Foo*)malloc(sizeof(Foo));
    if (!reflectedFoo) {
        fprintf(stderr, "Memory allocation failed\n");
        return EXIT_FAILURE;
    }

    const char* methodName = "printHello";
    Method m = findMethodByName(methodName);

    if (m) {
        m(reflectedFoo);
    } else {
        fprintf(stderr, "Method '%s' not found\n", methodName);
    }

    free(reflectedFoo);
    return EXIT_SUCCESS;
}
</syntaxhighlight>

=== C++ ===
The following is an example in [C++](/source/C%2B%2B) (using reflection added in [C++26](/source/C%2B%2B26)).<ref>{{Cite web|title=Standard library header <meta> (C++26)|url=https://en.cppreference.com/cpp/header/meta|author=cppreference.com|publisher=cppreference.com|website=cppreference.com|access-date=17 May 2026}}</ref>

<syntaxhighlight lang="cpp">
import std;

using std::string_view;
using std::views::filter;
using namespace std::meta;

consteval bool isNonstaticMethod(info mem) noexcept {
    return is_class_member(mem) && !is_static_member(mem) && is_function(mem);
}

consteval info findMethod(info type, string_view name) {
    for (info member : members_of(type, access_context::current())
        | filter(isNonstaticMethod)) {
        if (has_identifier(member) && identifier_of(member) == name) {
            return member;
        }
    }
    // Note: this is std::meta::exception, not std::exception
    throw exception(std::format("Failed to retrieve method {} from type {}", name, identifier_of(type)), ^^findMethod);
}

template <info T, const char* Name>
constexpr auto createInvokerImpl = []() -> auto {
    static constexpr info M = findMethod(T, Name);
    contract_assert(
        parameters_of(M).size() == 0 &&
        return_type_of(M) == ^^void
    );
    return []([:T:]& instance) -> void { instance.[:M:](); };
}();

consteval info createInvoker(info type, string_view name) {
    return substitute(^^createInvokerImpl, { reflect_constant(type), reflect_constant_string(name) });
}

class Foo {
private:
    // ...
public:
    Foo() = default;

    void printHello() const {
        std::println("Hello, world!");
    }
};

int main(int argc, char* argv[]) {
    Foo foo;

    // Without reflection
    foo.printHello();

    // With reflection
    auto invokePrint = [:createInvoker(^^Foo, "printHello"):];
    invokePrint(foo);

    return 0;
}
</syntaxhighlight>

=== C# ===
The following is an example in [C#](/source/C_Sharp_(programming_language)):

<syntaxhighlight lang="c#">
namespace Wikipedia.Examples;

using System;
using System.Reflection;

class Foo
{
    // ...

    public Foo() {}

    public void PrintHello()
    {
        Console.WriteLine("Hello, world!");
    }
}

public class InvokeFooExample
{
    static void Main(string[] args)
    {
        // Without reflection
        Foo foo = new();
        foo.PrintHello();

        // With reflection
        Object reflectedFoo = Activator.CreateInstance(typeof(Foo));
        MethodInfo method = reflectedFoo.GetType()
            .GetMethod("PrintHello");
        method.Invoke(foo, null);
    }
}
</syntaxhighlight>

===Delphi, Object Pascal===
This [Delphi](/source/Delphi_(software)) and [Object Pascal](/source/Object_Pascal) example assumes that a {{mono|TFoo}} class has been declared in a unit called {{mono|Unit1}}:

<syntaxhighlight lang="Delphi">
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;
</syntaxhighlight>

===eC===
The following is an example in eC:

<syntaxhighlight lang=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);
</syntaxhighlight>

===Go===
The following is an example in [Go](/source/Go_(programming_language)):

<syntaxhighlight lang="go">
import (
    "fmt"
    "reflect"
)

type Foo struct{}

func (f Foo) Hello() {
    fmt.Println("Hello, world!")
}

func main() {
    // Without reflection
    var f Foo
    f.Hello()

    // With reflection
    var fT reflect.Type = reflect.TypeOf(Foo{})
    var fV reflect.Value = reflect.New(fT)

    var m reflect.Value = fV.MethodByName("Hello")

    if m.IsValid() {
        m.Call(nil)
    } else {
        fmt.Println("Method not found")
    }
}
</syntaxhighlight>

===Java===
The following is an example in [Java](/source/Java_(programming_language)):
<syntaxhighlight lang="java">
package org.wikipedia.examples;

import java.lang.reflect.Method;

class Foo {
    // ...
    public Foo() {}

    public void printHello() {
       System.out.println("Hello, world!");
    }
}

public class InvokeFooExample {
    public static void main(String[] args) {
        // Without reflection
        Foo foo = new Foo();
        foo.printHello();

        // With reflection
        try {
            Foo reflectedFoo = Foo.class
                .getDeclaredConstructor()
                .newInstance();

            Method m = reflectedFoo.getClass()
                .getDeclaredMethod("printHello", new Class<?>[0]);
            m.invoke(reflectedFoo);
        } catch (ReflectiveOperationException e) {
            System.err.printf("An error occurred: %s%n", e.getMessage());
        }
    }
}
</syntaxhighlight>

Java also provides an internal class (not officially in the [Java Class Library](/source/Java_Class_Library)) in [module](/source/Java_Platform_Module_System) <code>jdk.unsupported</code>, <code>sun.reflect.Reflection</code> which is used by [<code>sun.misc.Unsafe</code>](/source/Security_of_the_Java_software_platform). It contains one method, {{java|static Class<?> getCallerClass(int depth)}} for obtaining the class making a call at a specified depth.<ref>{{Cite web|title=Reflection (Java Platform SE 9)|url=https://cr.openjdk.org/~jjg/java-javafx-jdk-docs/api/sun/reflect/Reflection.html|publisher=OpenJDK|website=cr.openjdk.org|access-date=10 October 2025}}</ref> This is now superseded by using the class <code>java.lang.StackWalker.StackFrame</code> and its method {{java|Class<?> getDeclaringClass()}}.

===JavaScript/TypeScript===
The following is an example in [JavaScript](/source/JavaScript):

<syntaxhighlight lang="javascript">
import 'reflect-metadata';

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

The following is the same example in [TypeScript](/source/TypeScript):

<syntaxhighlight lang="typescript">
import 'reflect-metadata';

// Without reflection
const foo: Foo = new Foo();
foo.hello();

// With reflection
const foo: Foo = Reflect.construct(Foo);
const hello: (this: Foo) => void = Reflect.get(foo, 'hello') as (this: Foo) => void;
Reflect.apply(hello, foo, []);

// With eval
eval('new Foo().hello()');
</syntaxhighlight>

===Julia===
The following is an example in [Julia](/source/Julia_(programming_language)):
<syntaxhighlight lang="julia-repl">
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
</syntaxhighlight>

===Kotlin===
Using Java reflection:
<syntaxhighlight lang="kotlin">
package org.wikipedia.examples

import java.lang.reflect.Method

class Foo {
    // ...
    constructor()

    fun printHello() {
        println("Hello, world!")
    }
}

fun main(args: Array<String>) {
    // Without reflection
    val foo = Foo()
    foo.printHello()

    // With reflection
    try {
        // Foo::class.java retrieves a java.lang.Class<Foo>
        val reflectedFoo = Foo::class.java
            .getDeclaredConstructor()
            .newInstance()

        val m: Method = reflectedFoo.javaClass
            .getDeclaredMethod("printHello")

        m.invoke(reflectedFoo)
    } catch (e: ReflectiveOperationException) {
        System.err.printf("An error occurred: %s%n", e.message)
    }
}
</syntaxhighlight>

Using pure Kotlin:
<syntaxhighlight lang="kotlin">
package org.wikipedia.examples

import kotlin.reflect.full.createInstance
import kotlin.reflect.full.functions

class Foo {
    // ...
    fun printHello() {
        println("Hello, world!")
    }
}

fun main(args: Array<String>) {
    // Without reflection
    val foo = Foo()
    foo.printHello()

    // With reflection
    try {
        val kClass = Foo::class
        val reflectedFoo = kClass.createInstance()
        val function = kClass.functions.first { it.name == "printHello" }
        function.call(reflectedFoo)
    } catch (e: Exception) {
        System.err.printf("An error occurred: %s%n", e.message)
    }
}
</syntaxhighlight>

===Objective-C===
The following is an example in [Objective-C](/source/Objective-C), implying either the [OpenStep](/source/OpenStep) or [Foundation Kit](/source/Foundation_Kit) framework is used:

<syntaxhighlight lang="ObjC">
// 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)];
</syntaxhighlight>

===Perl===
The following is an example in [Perl](/source/Perl):

<syntaxhighlight lang="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;";
</syntaxhighlight>

===PHP===
The following is an example in [PHP](/source/PHP):<ref>{{cite web |title=PHP: ReflectionClass - Manual |url=https://www.php.net/manual/en/class.reflectionclass.php |website=www.php.net}}</ref>

<syntaxhighlight lang="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);
</syntaxhighlight>

===Python===
The following is an example in [Python](/source/Python_(programming_language)):

<syntaxhighlight lang="python">
from typing import Any

class Foo:
    # ...
    def print_hello(self) -> None:
        print("Hello, world!")

if __name__ == "__main__":
    # Without reflection
    obj: Foo = Foo()
    obj.print_hello()

    # With reflection
    obj: Foo = globals()["Foo"]()
    _: Any = getattr(obj, "print_hello")()

    # With eval
    eval("Foo().print_hello()")
</syntaxhighlight>

===R===
The following is an example in [R](/source/R_(programming_language)):

<syntaxhighlight lang="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))
</syntaxhighlight>

===Ruby===
The following is an example in [Ruby](/source/Ruby_(programming_language)):

<syntaxhighlight lang="ruby">
# Without reflection
obj = Foo.new
obj.hello

# With reflection
obj = Object.const_get("Foo").new
obj.send :hello

# With eval
eval "Foo.new.hello"
</syntaxhighlight>

===Rust===
[Rust](/source/Rust_(programming_language)) does not have compile-time reflection in the standard library, but it is possible using some third-party libraries such as "{{mono|bevy_reflect}}".<ref>{{Cite web|title=bevy_reflect - Rust|url=https://docs.rs/bevy_reflect/latest/bevy_reflect/|website=docs.rs|date=30 May 2025}}</ref>

<syntaxhighlight lang="rust">
use std::any::TypeId;

use bevy_reflect::prelude::*;
use bevy_reflect::{
    FunctionRegistry,
    GetTypeRegistration,
    Reflect, 
    ReflectFunction,
    ReflectFunctionRegistry,
    ReflectMut, 
    ReflectRef, 
    TypeRegistry
};

#[derive(Reflect)]
#[reflect(DoFoo)]
struct Foo {
    // ...
}

impl Foo {
    fn new() -> Self {
        Foo {}
    }

    fn print_hello(&self) {
        println!("Hello, world!");
    }
}

#[reflect_trait]
trait DoFoo {
    fn print_hello(&self);
}

impl DoFoo for Foo {
    fn print_hello(&self) {
        self.print_hello();
    }
}

fn main() {
    // Without reflection
    let foo: Foo = Foo::new();
    foo.print_hello();

    // With reflection
    let mut registry: TypeRegistry = TypeRegistry::default();

    registry.register::<Foo>();
    registry.register_type_data::<Foo, ReflectFunctionRegistry>();
    registry.register_type_data::<Foo, ReflectDoFoo>();

    let foo: Foo = Foo;
    let reflect_foo: Box<dyn Reflect> = Box::new(foo);

    // Version 1: call hello by trait
    let trait_registration: &ReflectDoFoo = registry
        .get_type_data::<ReflectDoFoo>(TypeId::of::<Foo>())
        .expect("ReflectDoFoo not found for Foo");

    let trait_object: &dyn DoFoo = trait_registration
        .get(&*reflect_foo)
        .expect("Failed to get DoFoo trait object");

    trait_object.print_hello();

    // Version 2: call hello by function name
    let func_registry: &FunctionRegistry = registry
        .get_type_data::<FunctionRegistry>(TypeId::of::<Foo>())
        .expect("FunctionRegistry not found for Foo");

    if let Some(dyn_func) = func_registry.get("print_hello") {
        let result: Option<Box<dyn Reflect>> = dyn_func
            .call(&*reflect_foo, Vec::<Box<dyn Reflect>>::new())
            .ok();

        if result.is_none() {
            println!("Function called, no result returned (as expected for void return)");
        }
    } else {
        println!("No function named hello found in FunctionRegistry");
    }
}
</syntaxhighlight>

===Xojo===
The following is an example using [Xojo](/source/Xojo):

<syntaxhighlight lang="vbnet">
' 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
</syntaxhighlight>

==See also==
* [List of reflective programming languages and platforms](/source/List_of_reflective_programming_languages_and_platforms)
* [Mirror (programming)](/source/Mirror_(programming))
* [Programming paradigm](/source/Programming_paradigm)s
* [Self-hosting (compilers)](/source/Self-hosting_(compilers))
* [Self-modifying code](/source/Self-modifying_code)
* [Type introspection](/source/Type_introspection)
* [typeof](/source/typeof)

== References ==
=== Citations ===
{{Reflist}}

=== Sources ===
{{refbegin}}
* Jonathan M. Sobel and Daniel P. Friedman. [https://web.archive.org/web/20100204091328/http://www.cs.indiana.edu/~jsobel/rop.html ''An Introduction to Reflection-Oriented Programming''] (1996), [Indiana University](/source/Indiana_University).
* [https://www.codeproject.com/Articles/674455/Anti-Reflector-NET-Code-Protection Anti-Reflection technique using C# and C++/CLI wrapper to prevent code thief]
{{refend}}

==Further reading==
* Ira R. Forman and Nate Forman, ''Java Reflection in Action'' (2005), {{ISBN|1-932394-18-4}}
* Ira R. Forman and Scott Danforth, ''Putting Metaclasses to Work'' (1999), {{ISBN|0-201-43305-2}}

==External links==
* [https://www-master.ufr-info-p6.jussieu.fr/2007/Ajouts/Master_esj20_2007_2008/IMG/pdf/malenfant-ijcai95.pdf Reflection in logic, functional and object-oriented programming: a short comparative study]
* [https://web.archive.org/web/20100204091328/http://www.cs.indiana.edu/~jsobel/rop.html An Introduction to Reflection-Oriented Programming]
* [http://www.laputan.org/#Reflection Brian Foote's pages on Reflection in Smalltalk]
* [http://docs.oracle.com/javase/tutorial/reflect/index.html Java Reflection API Tutorial] from Oracle
{{Programming paradigms navbox}}
{{Types of programming languages}}

{{DEFAULTSORT:Reflection (Computer Programming)}}
Category:Programming constructs
Category:Programming language comparisons
<!-- Hidden categories below -->
Category:Articles with example BASIC code
Category:Articles with example C code
Category:Articles with example C Sharp code
Category:Articles with example Java code
Category:Articles with example JavaScript code
Category:Articles with example Julia code
Category:Articles with example Lisp (programming language) code
Category:Articles with example Objective-C code
Category:Articles with example Pascal code
Category:Articles with example Perl code
Category:Articles with example PHP code
Category:Articles with example Python (programming language) code
Category:Articles with example R code
Category:Articles with example Ruby code

---
Adapted from the Wikipedia article [Reflective programming](https://en.wikipedia.org/wiki/Reflective_programming) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/Reflective_programming?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
