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
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 • include • include 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* 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; }
C++ The following is an example in
C++ (using reflection added in
C++26). 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 auto 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 members = std::meta::members_of(type, ctx); template for (constexpr Info member : members | Filter(isNonstaticMethod)) { if (std::meta::has_identifier(member) && std::meta::identifier_of(member) == name) { return member; } } throw ReflectionException(std::format("Failed to retrieve method {} from type {}", name, std::meta::identifier_of(type)), ^^findMethod); } template constexpr auto createInvokerImpl = []() -> auto { using ReflectedType = [:Type:]; static constexpr Info M = findMethod(Type, Name); contract_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 reflectedFoo = Activator.CreateInstance(typeof(Foo)); MethodInfo method = reflectedFoo.GetType() .GetMethod("PrintHello"); method.Invoke(foo, null); } }
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('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.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()); } } } 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, 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(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
Kotlin Using Java reflection: package org.wikipedia.examples import java.lang.reflect.Method class Foo { // ... constructor() fun printHello() { println("Hello, world!") } } fun main(args: Array) { // Without reflection val foo = Foo() foo.printHello() // With reflection try { // Foo::class.java retrieves a java.lang.Class 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) } } Using pure 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) { // 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) } }
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: // 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
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 "". 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::(); registry.register_type_data::(); registry.register_type_data::(); let foo: Foo = Foo; let reflect_foo: Box = Box::new(foo); // Version 1: call hello by trait let trait_registration: &ReflectDoFoo = registry .get_type_data::(TypeId::of::()) .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::(TypeId::of::()) .expect("FunctionRegistry not found for Foo"); if let Some(dyn_func) = func_registry.get("print_hello") { let result: Option> = dyn_func .call(&*reflect_foo, Vec::>::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==