Reflective programming: Difference between revisions

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search
imported>Bossgamer10987
Python: Changed print_hello method to include a self parameter. Previously the lack of a parameter or @staticmethod preceding the method meant that running the code provided would throw a TypeError due to a positional argument being provided with no parameter to accept it.
 
Line 7: Line 7:
The earliest computers were programmed in their native [[assembly language]]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]] such as [[ALGOL]], [[COBOL]], [[Fortran]], [[Pascal (programming language)|Pascal]], and [[C (programming language)|C]], this reflective ability largely disappeared until new programming languages with reflection built into their type systems appeared.{{Citation needed|date=July 2015}}
The earliest computers were programmed in their native [[assembly language]]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]] such as [[ALGOL]], [[COBOL]], [[Fortran]], [[Pascal (programming language)|Pascal]], and [[C (programming language)|C]], 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]]'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]].<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>
[[Brian Cantwell Smith]]'s 1982 doctoral dissertation introduced the notion of computational reflection in [[Procedural programming|procedural]] [[programming languages]] and the notion of the [[meta-circular interpreter]] as a component of 3-[[Lisp (programming language)|Lisp]].<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==
==Uses==
Line 18: Line 18:
Reflection can be used for observing and modifying program execution at [[Runtime (program lifecycle phase)|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.
Reflection can be used for observing and modifying program execution at [[Runtime (program lifecycle phase)|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 (programming language)|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.
In [[object-oriented programming]] languages such as [[Java (programming language)|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 (computing)|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 object]]s.
Reflection is often used as part of [[software testing]], such as for the runtime creation/instantiation of [[mock object]]s.
Line 65: Line 65:
   (funcall (sb-mop:method-generic-function print-hello-method)
   (funcall (sb-mop:method-generic-function print-hello-method)
           (make-instance foo-class)))
           (make-instance foo-class)))
</syntaxhighlight>
=== C ===
Reflection is not possible in [[C (programming language)|C]], 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]] 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]]
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* fooReflected = malloc(sizeof(Foo));
    if (!fooReflected) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }
    const char* methodName = "printHello";
    Method m = findMethodByName(methodName);
    if (m) {
        m(fooReflected);
    } else {
        fprintf(stderr, "Method '%s' not found\n", methodName);
    }
    free(fooReflected);
    return 0;
}
</syntaxhighlight>
</syntaxhighlight>


=== C++ ===
=== C++ ===
The following is an example in [[C++]].
The following is an example in [[C++]] (using reflection added in [[C++26]]).


<syntaxhighlight lang="cpp">
<syntaxhighlight lang="cpp">
import std;
import std;


using StringView = std::string_view;
template <typename T>
using Vector = std::vector<T>;
using AccessContext = std::meta::access_context;
using ReflectionException = std::meta::exception;
using Info = std::meta::info;
using Info = std::meta::info;
using String = std::string;
inline constexpr decltype(std::views::filter) Filter = std::views::filter;


template <typename T>
[[nodiscard]]
using AlwaysFalse = std::always_false<T>;
consteval bool isNonstaticMethod(Info mem) noexcept {
template <typename T, T v>
    return std::meta::is_class_member(mem)
using IntegralConstant = std::integral_constant<T, v>;
        && !std::meta::is_static_member(mem)
template <typename T>
        && std::meta::is_function(mem);
using Vector = std::vector<T>;
}


consteval auto makeInvoker(Info& refl, const String& methodName) {
[[nodiscard]]
     return [refl](auto&& instance) {
consteval info findMethod(Info type, StringView name) {
        constexpr Vector<Info> members = std::meta::nonstatic_members_of(refl);
     constexpr auto ctx = AccessContext::current();
        for (Info& member: members) {
    Vector<Info> members = std::meta::members_of(type, ctx);
            if (std::meta::identifier_of(member) == methodName) {
    for (Info member : members | Filter(isNonstaticMethod)) {
                return [&]<auto M>(IntegralConstant<decltype(member), M>) {
        if (std::meta::name_of(member) == name) {
                    instance.[:M: ]();
            return member;
                }(IntegralConstant<decltype(member), member>{});
            }
         }
         }
         static_assert(AlwaysFalse<decltype(instance)>(), "Method not found");
    }
     };
    throw ReflectionException(std::format("Failed to retrieve method {} from type {}", name, std::meta::name_of(type)), ^^findMethod);
}
 
template <Info Type, StringView Name>
constexpr auto createInvokerImpl = []() -> auto {
    using ReflectedType = [:Type:];
    static constexpr Info M = findMethod(ReflectedType, Name);
    static_assert(
        std::meta::parameters_of(M).size() == 0 &&
         std::meta::return_type_of(M) == ^^void
    );
    return [](ReflectedType& instance) -> void { instance.[:M:](); };
}();
 
[[nodiscard]]
consteval Info createInvoker(Info type, StringView name) {
     return std::meta::substitute(
        ^^createInvokerImpl,
        { std::meta::reflect_constant(type), std::meta::reflect_constant_string(name) }
    );
}
}
class Foo {
private:
    // ...
public:
    Foo() = default;
    void printHello() const noexcept {
        std::println("Hello, world!");
    }
};


int main(int argc, char* argv[]) {
int main(int argc, char* argv[]) {
Line 104: Line 205:


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


Line 116: Line 216:


<syntaxhighlight lang="c#">
<syntaxhighlight lang="c#">
// Without reflection
namespace Wikipedia.Examples;
var foo = new Foo();
 
foo.PrintHello();
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
        // With reflection
Object foo = Activator.CreateInstance("complete.classpath.and.Foo");
        Object foo = Activator.CreateInstance(typeof(Foo));
MethodInfo method = foo.GetType().GetMethod("PrintHello");
        MethodInfo method = foo.GetType().GetMethod("PrintHello");
method.Invoke(foo, null);
        method.Invoke(foo, null);
    }
}
</syntaxhighlight>
</syntaxhighlight>


Line 165: Line 288:
<syntaxhighlight lang=eC>
<syntaxhighlight lang=eC>
// Without reflection
// Without reflection
Foo foo { };
Foo foo{};
foo.hello();
foo.hello();


Line 172: Line 295:
Instance foo = eInstance_New(fooClass);
Instance foo = eInstance_New(fooClass);
Method m = eClass_FindMethod(fooClass, "hello", fooClass.module);
Method m = eClass_FindMethod(fooClass, "hello", fooClass.module);
((void (*)())(void *)m.function)(foo);
((void(*)())(void*)m.function)(foo);
</syntaxhighlight>
</syntaxhighlight>


Line 179: Line 302:


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


// Without reflection
type Foo struct{}
f := Foo{}
 
f.Hello()
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)


// With reflection
    var m reflect.Value = fV.MethodByName("Hello")
fT := reflect.TypeOf(Foo{})
fV := reflect.New(fT)


m := fV.MethodByName("Hello")
    if m.IsValid() {
if m.IsValid() {
        m.Call(nil)
    m.Call(nil)
    } else {
        fmt.Println("Method not found")
    }
}
}
</syntaxhighlight>
</syntaxhighlight>
Line 198: Line 335:
The following is an example in [[Java (programming language)|Java]]:
The following is an example in [[Java (programming language)|Java]]:
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
package org.wikipedia.example;
import java.lang.reflect.Method;
import java.lang.reflect.Method;


// Without reflection
class Foo {
Foo foo = new Foo();
    // ...
foo.hello();
    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
        // With reflection
try {
        try {
    Object foo = Foo.class.getDeclaredConstructor().newInstance();
            Foo foo = Foo.class.getDeclaredConstructor().newInstance();


    Method m = foo.getClass().getDeclaredMethod("hello", new Class<?>[0]);
            Method m = foo.getClass().getDeclaredMethod("printHello", new Class<?>[0]);
    m.invoke(foo);
            m.invoke(foo);
} catch (ReflectiveOperationException ignored) {}
        } catch (ReflectiveOperationException e) {
            System.err.printf("An error occurred: %s%n", e.getMessage());
        }
    }
}
</syntaxhighlight>
</syntaxhighlight>
Java also provides an internal class (not officially in the [[Java Class Library]]) in [[Java Platform Module System|module]] <code>jdk.unsupported</code>, <code>sun.reflect.Reflection</code> which is used by [[Security of the Java software platform#The sun.misc.Unsafe class|<code>sun.misc.Unsafe</code>]]. 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===
===JavaScript/TypeScript===
Line 217: Line 373:


<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
import 'reflect-metadata';
// Without reflection
// Without reflection
const foo = new Foo();
const foo = new Foo();
Line 233: Line 391:


<syntaxhighlight lang="typescript">
<syntaxhighlight lang="typescript">
import 'reflect-metadata';
// Without reflection
// Without reflection
const foo: Foo = new Foo();
const foo: Foo = new Foo();
Line 278: Line 438:


// Sending "hello" to a Foo instance without reflection.
// Sending "hello" to a Foo instance without reflection.
Foo *obj = [[Foo alloc] init];
Foo* obj = [[Foo alloc] init];
[obj hello];
[obj hello];


Line 331: Line 491:


<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
# Without reflection
from typing import Any
obj = Foo()
 
obj.hello()
class Foo:
    # ...
    def print_hello(self) -> None:
        print("Hello, world!")
 
if __name__ == "__main__":
    # Without reflection
    obj: Foo = Foo()
    obj.print_hello()


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


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


Line 372: Line 540:
# With eval
# With eval
eval "Foo.new.hello"
eval "Foo.new.hello"
</syntaxhighlight>
===Rust===
[[Rust (programming language)|Rust]] 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>
</syntaxhighlight>



Latest revision as of 07:51, 23 December 2025

Template:Short description Script error: No such module "Distinguish".

In computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior.[1]

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.Script error: No such module "Unsubst".

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.[2][3]

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

Script error: No such module "Unsubst". 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 constructions (such as code blocks, classes, methods, protocols, etc.) as first-class objects 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 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()[0] (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 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.[4] 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.[5]

Examples

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

Common Lisp

The following is an example in Common Lisp using the Common Lisp Object System:

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

C

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

#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]] 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]]
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* fooReflected = malloc(sizeof(Foo));
    if (!fooReflected) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

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

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

    free(fooReflected);
    return 0;
}

C++

The following is an example in C++ (using reflection added in C++26).

import std;

using StringView = std::string_view;
template <typename T>
using Vector = std::vector<T>;
using AccessContext = std::meta::access_context;
using ReflectionException = std::meta::exception;
using Info = std::meta::info;
inline constexpr decltype(std::views::filter) Filter = std::views::filter;

[[nodiscard]]
consteval bool isNonstaticMethod(Info mem) noexcept {
    return std::meta::is_class_member(mem) 
        && !std::meta::is_static_member(mem)
        && std::meta::is_function(mem);
}

[[nodiscard]]
consteval info findMethod(Info type, StringView name) {
    constexpr auto ctx = AccessContext::current();
    Vector<Info> members = std::meta::members_of(type, ctx);
    for (Info member : members | Filter(isNonstaticMethod)) {
        if (std::meta::name_of(member) == name) {
            return member;
        }
    }
    throw ReflectionException(std::format("Failed to retrieve method {} from type {}", name, std::meta::name_of(type)), ^^findMethod);
}

template <Info Type, StringView Name>
constexpr auto createInvokerImpl = []() -> auto {
    using ReflectedType = [:Type:];
    static constexpr Info M = findMethod(ReflectedType, Name);
    static_assert(
        std::meta::parameters_of(M).size() == 0 && 
        std::meta::return_type_of(M) == ^^void
    );
    return [](ReflectedType& instance) -> void { instance.[:M:](); };
}();

[[nodiscard]]
consteval Info createInvoker(Info type, StringView name) {
    return std::meta::substitute(
        ^^createInvokerImpl, 
        { std::meta::reflect_constant(type), std::meta::reflect_constant_string(name) }
    );
}

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

    void printHello() const noexcept {
        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;
}

C#

The following is an example in 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 foo = Activator.CreateInstance(typeof(Foo));
        MethodInfo method = foo.GetType().GetMethod("PrintHello");
        method.Invoke(foo, null);
    }
}

Delphi, Object Pascal

This Delphi and Object Pascal example assumes that a <templatestyles src="Mono/styles.css" />TFoo class has been declared in a unit called <templatestyles src="Mono/styles.css" />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;

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

Go

The following is an example in 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")
    }
}

Java

The following is an example in Java:

package org.wikipedia.example;

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 foo = Foo.class.getDeclaredConstructor().newInstance();

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

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

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(Foo);
const hello = Reflect.get(foo, 'hello');
Reflect.apply(hello, foo, []);

// With eval
eval('new Foo().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(Foo);
const hello: (this: Foo) => void = Reflect.get(foo, 'hello') as (this: Foo) => void;
Reflect.apply(hello, foo, []);

// With eval
eval('new Foo().hello()');

Julia

The following is an example in Julia:

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] init];
[obj hello];

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

// 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:

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

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
obj = Object.const_get("Foo").new
obj.send :hello

# With eval
eval "Foo.new.hello"

Rust

Rust does not have compile-time reflection in the standard library, but it is possible using some third-party libraries such as "<templatestyles src="Mono/styles.css" />bevy_reflect".[8]

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");
    }
}

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

References

Citations

<templatestyles src="Reflist/styles.css" />

  1. Script error: No such module "citation/CS1".
  2. Brian Cantwell Smith, Procedural Reflection in Programming Languages, Department of Electrical Engineering and Computer Science, Massachusetts Institute of Technology, PhD dissertation, 1982.
  3. Brian C. Smith. Reflection and semantics in a procedural language Template:Webarchive. Technical Report MIT-LCS-TR-272, Massachusetts Institute of Technology, Cambridge, Massachusetts, January 1982.
  4. Script error: No such module "citation/CS1".
  5. Script error: No such module "Citation/CS1".
  6. Script error: No such module "citation/CS1".
  7. Script error: No such module "citation/CS1".
  8. Script error: No such module "citation/CS1".

Script error: No such module "Check for unknown parameters".

Sources

<templatestyles src="Refbegin/styles.css" />

Further reading

  • Ira R. Forman and Nate Forman, Java Reflection in Action (2005), Template:ISBN
  • Ira R. Forman and Scott Danforth, Putting Metaclasses to Work (1999), Template:ISBN

External links

Template:Programming paradigms navbox Script error: No such module "Navbox".