Programming Search⌘K

Conceptcore

Runtime reflection

Also called reflection, reflective programming, introspection, type introspection.

The ability of a running program to examine its own structure, such as the type of a value, its fields and its methods, and to use them by name.

Applies to
core-languages

Idea

A compiler knows the types, fields and methods of a program. In many languages this knowledge is gone when the program runs: the machine code has addresses and offsets, not names. Runtime reflection keeps a description of the program in memory and gives the program access to it. Rob Pike puts it in one sentence: "Reflection in computing is the ability of a program to examine its own structure, particularly through types; it's a form of metaprogramming."2

With reflection, one piece of code can handle types that it has never seen. A serializer can write any object as JSON by walking its fields. A test framework can find every method whose name starts with test. A dependency injection container can call a constructor that it found by name in a configuration file. The Java tutorial lists class browsers, debuggers, test tools and extensibility through class names as the uses.5

The Go program below prints any struct without knowing its type. It asks the value for its type, then asks the type for its fields.

package main

import (
	"fmt"
	"reflect"
)

type User struct {
	Name  string
	Age   int
	Admin bool
}

type Order struct {
	ID    int
	Total float64
}

func describe(v any) {
	t := reflect.TypeOf(v)
	val := reflect.ValueOf(v)
	fmt.Println(t.Name())
	for i := 0; i < t.NumField(); i++ {
		fmt.Printf("  %s (%s) = %v\n", t.Field(i).Name, t.Field(i).Type, val.Field(i))
	}
}

func main() {
	describe(User{"Ada", 36, true})
	describe(Order{7, 19.5})
}
Output
User
  Name (string) = Ada
  Age (int) = 36
  Admin (bool) = true
Order
  ID (int) = 7
  Total (float64) = 19.5

The price is that the compiler can no longer check the code. A field or a method named by a string may not exist, and the error appears only when the program runs. Reflective code is also slower, and it can reach parts of an object that its author meant to hide.

How it works

The description of the program

A language with reflection keeps one object for each type at run time: java.lang.Class in Java, System.Type in .NET, reflect.Type in Go and the class object in Python. Each value can return its type object. In Java the call is getClass(), in C# GetType(), in Go reflect.TypeOf and in Python type. The type object then lists the members, and each member is an object too: Java has Field, Method and Constructor, and .NET has FieldInfo, PropertyInfo, MethodInfo and ConstructorInfo.69

A member object can do two things. It can describe the member: its name, its type, its parameters and its modifiers. And it can use the member on a given object: read or set a field, or call a method with an array of arguments.9 In Go, reflect.ValueOf returns a reflect.Value that holds the data, and methods on the value read it, set it and call it.3

Pike states the Go rules as three laws. Reflection goes from an interface value to a reflection object. Reflection goes from a reflection object back to an interface value. To modify a reflection object, the value must be settable.2 The third law explains a common panic. reflect.ValueOf(x) receives a copy of x, so a change to it could not change x, and a call to SetFloat panics with "reflect.Value.SetFloat using unaddressable value". A reflection value made from &x and Elem() is settable.2 The Go example not-settable shows the panic, and settable shows the fix.

Where the information comes from

Reflection needs a description of the program at run time. In .NET, assemblies contain modules, modules contain types, and types contain members, and reflection provides objects that encapsulate each of them.9 Go keeps struct tags for reflection alone. The Go specification says that tags "are made visible through a reflection interface" and are "otherwise ignored".4 Python and JavaScript keep all of it by design, because objects are tables of named attributes.

Languages that compile to machine code without this metadata have little or no reflection. In C++, typeid gives a std::type_info for the dynamic type of a polymorphic object, and dynamic_cast tests it.19 The result of type_info::name() is "an implementation-defined ntbs".19 There is no list of fields or methods. Rust's std::any describes itself as "utilities for dynamic typing or type reflection". It can give a TypeId and can test whether a dyn Any holds a given concrete type, but it "cannot be used to test whether a type implements a trait".18

TypeScript erases its types. The handbook says: "Type annotations never change the runtime behavior of your program."17 A TypeScript interface does not exist at run time, so a TypeScript program can only reflect on the JavaScript objects.

Reflection in dynamic languages

In Python, every attribute access is already a lookup by name at run time. The built-in getattr(x, 'foobar') is equivalent to x.foobar, and it raises AttributeError if the attribute does not exist.14 The module inspect gets information about live objects: modules, classes, methods, functions, tracebacks, frames and code objects.13 inspect.signature reads the parameters of a function and their annotations.13 Python keeps type hints at run time, but it does not enforce them.15

JavaScript exposes the same model through the Reflect object. Reflect is an ordinary object that cannot be called or constructed. Its functions, such as Reflect.apply, Reflect.get and Reflect.ownKeys, perform the internal operations of objects.16

In these languages reflection can change the program as well as read it. Python's setattr adds an attribute to an object, and an assignment to a class attribute adds a method to every instance. The Python example change shows both.

Smith's procedural reflection

Brian Cantwell Smith's 1982 thesis asked a larger question. He wanted a computational system that could "reason" about its own inferential processes.1 He noted that "the term 'reflection' does not name a previously well-defined question", and so he had to give an account of what reflection is.1 His system had to make "fully articulated descriptions of the state of the reasoning process" available "for inspection and modification" at any point, and it had to resume the computation from such descriptions.1 He called this particular form "procedural reflection".1 He built three dialects of Lisp, and the third, 3-LISP, was "endowed with reflective powers".1

The reflection of Java, C#, Go and Python is a much smaller part of this idea. It describes the structure of the program, its types and members. It does not, in general, give access to the state of the interpreter that runs the program.

In languages

LanguageVerdictNote
PythonNative
C++Absent
JavaNative
CAbsentA C program has no type information at run time. Alternative: A table of field names, offsets and types, written by hand or by a generator.
C#Native
JavaScriptNative
TypeScriptAbsent
GoNative
RustAbsent
KotlinNativeThe language reference describes class references with ::class and callable references; the library kotlin-reflect adds full introspection. No example file because kotlinc is not installed on the machine that recorded the examples.
SQLIdiomThe standard information schema describes tables and columns as tables that a query can read.
BashAbsentThe shell has strings and arrays, not objects with types.
PowerShellNativePowerShell runs on .NET and objects expose their members; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no program to inspect.
CSSDoes not applyStyle rules have no program to inspect.
Regular expressionsDoes not applyA pattern has no types or members.
Language Verdict Form
Java native Class, java.lang.reflect; access checks apply, setAccessible subject to modules
C# native System.Type, System.Reflection; limited by trimming
Go native package reflect: TypeOf, ValueOf, struct tags
Python native type, getattr, setattr, vars, the module inspect
JavaScript native typeof, Object.keys, prototypes, the Reflect object
TypeScript absent types are erased; the reflection of JavaScript only
Kotlin native ::class, callable references; the library kotlin-reflect
C++ absent typeid and dynamic_cast only; no members at run time
Rust absent std::any: TypeId, type_name, downcasting
C absent no type information at run time
PowerShell native objects of .NET; Get-Member lists properties and methods
Bash absent strings and arrays, no typed objects
SQL idiom the information schema describes tables and columns
Regex n/a no types or members
HTML/CSS n/a no program to inspect

Java keeps access control in reflection. Every reflected object checks that the code using it may access the member, and setAccessible(true) can suppress the check only in some cases: the caller and the member are in the same module, the member is public in an exported package, or the package is open to the caller.7 The Java example encapsulation shows the call failing for a private field of String, and private-own shows it working for a class of the program. Order is not guaranteed: "The elements in the returned array are not sorted and are not in any particular order" for getDeclaredFields.6 getRecordComponents is the exception. It returns the components "in the same order that they are declared".6

C# reflection can load assemblies, find types and create instances, and the classes of System.Reflection.Emit can build types at run time.9 Before .NET 7, GetProperties returned the properties in no particular order. From .NET 7, the order is "deterministic based upon the metadata ordering in the assembly".10

Kotlin has class references (ClassName::class and value::class) and callable references in the language and the standard library. For more extensive introspection, a program adds the library kotlin-reflect. On the JVM, this is a separate artifact, so that applications without reflection can leave it out and reduce the size of the classpath.20 No Kotlin example runs on this page, because kotlinc is not installed on the machine that recorded the examples.

PowerShell works on .NET objects, and the cmdlet Get-Member "gets the members, the properties and methods, of objects".21 SQL describes a database to itself through the information schema, a set of views that "is defined in the SQL standard".22 A query on information_schema.columns is reflection over the tables of the database.

PythonGitHub
import inspect
from dataclasses import dataclass, fields


@dataclass
class Point:
    x: int
    y: int

    def total(self, scale: int = 1) -> int:
        return (self.x + self.y) * scale


p = Point(3, 4)
print("type:", type(p).__name__)
for f in fields(p):
    print(f.name, ":", f.type.__name__, "=", getattr(p, f.name))
method = getattr(p, "total")
print("signature:", inspect.signature(method))
print("total(2) =", method(2))
print("attributes:", vars(p))
Output
type: Point
x : int = 3
y : int = 4
signature: (scale: int = 1) -> int
total(2) = 14
attributes: {'x': 3, 'y': 4}

Every object carries its class, and the class carries its methods. getattr looks up an attribute by a name that is a string. inspect.signature reads the parameters and their annotations.

This code raises AttributeError, on purpose.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def total(self):
        return self.x + self.y


p = Point(3, 4)
print(getattr(p, "totl")())

A misspelled name is an error only when the line runs. In Python this is true of ordinary attribute access as well, so reflection changes less than in a statically typed language.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y


p = Point(3, 4)
setattr(p, "z", 5)
Point.norm1 = lambda self: abs(self.x) + abs(self.y)
print(vars(p))
print(p.norm1())
Output
{'x': 3, 'y': 4, 'z': 5}
7

Python reflection can change the program as well as read it. setattr adds an attribute to one object, and an assignment to the class adds a method to every instance.

  • Verdict: native. type, getattr, setattr, hasattr, vars and dir are built-in functions, and the module inspect reads signatures, source code and stack frames.
  • Annotations are kept at run time, so inspect.signature and dataclasses.fields can report the declared types. Python does not enforce them.
#include <iostream>
#include <memory>
#include <typeinfo>

struct Shape {
    virtual ~Shape() = default;
    virtual double area() const = 0;
};

struct Square : Shape {
    double side;
    explicit Square(double s) : side(s) {}
    double area() const override { return side * side; }
};

struct Circle : Shape {
    double r;
    explicit Circle(double radius) : r(radius) {}
    double area() const override { return 3.0 * r * r; }
};

int main() {
    std::unique_ptr<Shape> shapes[] = {std::make_unique<Square>(2.0), std::make_unique<Circle>(1.0)};
    for (const auto& s : shapes) {
        const Shape& ref = *s;
        std::cout << "is a Square: " << std::boolalpha << (typeid(ref) == typeid(Square));
        if (auto* sq = dynamic_cast<const Square*>(&ref)) {
            std::cout << ", side = " << sq->side;
        }
        std::cout << '\n';
    }
}
Output
is a Square: true, side = 2
is a Square: false

typeid on a reference to a polymorphic class gives the dynamic type, and dynamic_cast tests it. Neither can list the members of Square. The text of typeid(...).name() is implementation-defined, so this program compares type_info objects instead of printing names.

  • Verdict: absent. C++ has run-time type identification (typeid, std::type_info and dynamic_cast) but no run-time access to fields or methods by name.
  • Programs that need the members of a class write the list by hand or generate it with a tool.
JavaGitHub
import java.lang.reflect.Method;
import java.lang.reflect.RecordComponent;

public class Main {
    record Point(int x, int y) {
        int sum() {
            return x + y;
        }
    }

    public static void main(String[] args) throws Exception {
        Object p = new Point(3, 4);
        Class<?> c = p.getClass();
        System.out.println("class: " + c.getSimpleName());
        for (RecordComponent rc : c.getRecordComponents()) {
            Object value = rc.getAccessor().invoke(p);
            System.out.println(rc.getName() + " : " + rc.getType() + " = " + value);
        }
        Method sum = c.getDeclaredMethod("sum");
        System.out.println("sum() = " + sum.invoke(p));
    }
}
Output
class: Point
x : int = 3
y : int = 4
sum() = 7

The program never names x, y or sum in a call that the compiler checks. It finds the components and the method at run time, from the Class object of the value. getRecordComponents returns the components in the order of declaration. getDeclaredFields and getDeclaredMethods promise no order.

This code raises NoSuchMethodException, on purpose.

public class Main {
    record Point(int x, int y) {
        int sum() {
            return x + y;
        }
    }

    public static void main(String[] args) throws Exception {
        Object p = new Point(3, 4);
        System.out.println(p.getClass().getDeclaredMethod("summ").invoke(p));
    }
}

The name of the method is a string, so the compiler cannot check it. The typo summ compiles, and the program fails when it runs. A direct call ((Point) p).summ() would not compile.

This code raises InaccessibleObjectException, on purpose.

import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) throws Exception {
        Field value = String.class.getDeclaredField("value");
        value.setAccessible(true);
        System.out.println(value.get("abc"));
    }
}

setAccessible(true) turns off the access checks for a private member, but only if the package of the member is open to the caller. java.lang in the module java.base is not open to the unnamed module of this program, so the call throws.

import java.lang.reflect.Field;

public class Main {
    static class Account {
        private int balance = 100;
    }

    public static void main(String[] args) throws Exception {
        Account a = new Account();
        Field f = Account.class.getDeclaredField("balance");
        f.setAccessible(true);
        f.setInt(a, -5);
        System.out.println("balance = " + a.balance);
    }
}
Output
balance = -5

Within its own module, a program can open and change a private field. The class has no method that sets a negative balance, but reflection goes around it. This is the "exposure of internals" that the Java tutorial warns about.

  • Verdict: native. java.lang.Class and the package java.lang.reflect describe classes, fields, methods, constructors and record components at run time, and they can read fields, set fields and call methods.
  • Access control applies to reflection too. setAccessible can suppress it only for members of the caller's own module or of packages that are open to the caller.
  • Method.invoke wraps an exception from the called method in InvocationTargetException.
using System;
using System.Reflection;

object p = new Point(3, 4);
Type t = p.GetType();
Console.WriteLine($"type: {t.Name}");
foreach (PropertyInfo prop in t.GetProperties())
{
    Console.WriteLine($"{prop.Name} : {prop.PropertyType.Name} = {prop.GetValue(p)}");
}
MethodInfo sum = t.GetMethod("Sum")!;
Console.WriteLine($"Sum() = {sum.Invoke(p, null)}");

record Point(int X, int Y)
{
    public int Sum() => X + Y;
}
Output
type: Point
X : Int32 = 3
Y : Int32 = 4
Sum() = 7

GetType returns the run-time type of the value. GetProperties and GetMethod find its members by name, and GetValue and Invoke use them. The order of GetProperties is the metadata order of the assembly since .NET 7. Earlier versions gave no order.

This code raises NullReferenceException, on purpose.

using System;

object p = new Point(3, 4);
var sum = p.GetType().GetMethod("Summ");
Console.WriteLine(sum!.Invoke(p, null));

record Point(int X, int Y)
{
    public int Sum() => X + Y;
}

GetMethod returns null when no method has the name. The ! tells the compiler not to warn about it, so the typo shows up only as an exception at run time.

using System;
using System.Reflection;

var m = typeof(Parser).GetMethod("Parse")!;
try
{
    m.Invoke(null, new object[] { "x" });
}
catch (TargetInvocationException e)
{
    Console.WriteLine($"outer: {e.GetType().Name}");
    Console.WriteLine($"inner: {e.InnerException!.GetType().Name}");
}

static class Parser
{
    public static int Parse(string s) => int.Parse(s);
}
Output
outer: TargetInvocationException
inner: FormatException

An exception thrown by the method that Invoke calls arrives wrapped in TargetInvocationException. A catch (FormatException) around the call would not catch it.

  • Verdict: native. System.Type and the namespace System.Reflection describe assemblies, types, fields, properties, methods and attributes at run time.
  • Reflection and trimming do not mix well. The trimmer removes code that it cannot see used. A type loaded by a name that comes from input at run time cannot be analyzed, and the SDK reports a trim warning.
  • Generics checked at compile time are the first fix that the .NET documentation gives for a trim warning.
JavaScriptGitHub
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  sum() {
    return this.x + this.y;
  }
}

const p = new Point(3, 4);
console.log("constructor:", p.constructor.name);
console.log("own keys:", Reflect.ownKeys(p));
console.log("methods:", Object.getOwnPropertyNames(Object.getPrototypeOf(p)));
for (const key of Object.keys(p)) {
  console.log(key, typeof p[key], Reflect.get(p, key));
}
console.log("sum() =", Reflect.apply(p.sum, p, []));
console.log("has z:", Reflect.has(p, "z"));
Output
constructor: Point
own keys: [ 'x', 'y' ]
methods: [ 'constructor', 'sum' ]
x number 3
y number 4
sum() = 7
has z: false

An object is a table of properties, so reflection reads the table. Reflect.ownKeys lists the keys of the object itself, and the methods of a class live on its prototype.

This code runs but gives a wrong answer on purpose.

const point = { x: 3, y: 4 };
const key = "X";
console.log(point.x + Reflect.get(point, key));
Output
NaN

A key that does not exist gives undefined, not an error. 3 + undefined is NaN, and the program goes on with a wrong value.

  • Verdict: native. typeof, Object.keys, Object.getPrototypeOf and the Reflect object inspect and change objects at run time. Reflect is an ordinary object whose functions match the internal methods of objects.
  • JavaScript values have no declared types. Reflection sees properties and prototypes, not types.
TypeScriptGitHub
interface Shape {
  kind: string;
  area(): number;
}

class Square implements Shape {
  kind = "square";
  private side: number;
  constructor(side: number) {
    this.side = side;
  }
  area(): number {
    return this.side * this.side;
  }
}

const s: Shape = new Square(3);
console.log("constructor:", s.constructor.name);
console.log("keys:", Object.keys(s));
console.log("typeof area:", typeof s.area);
console.log("instanceof Square:", s instanceof Square);
Output
constructor: Square
keys: [ 'kind', 'side' ]
typeof area: function
instanceof Square: true

The interface Shape and the type annotations do not exist when the program runs. Reflection sees the JavaScript object: its class, its own keys and its prototype. The private field side is an ordinary property at run time, so Object.keys lists it.

  • Verdict: absent. TypeScript erases its types, and type annotations never change the run-time behavior of a program. The reflection that a TypeScript program can use is the reflection of JavaScript.
  • A test such as s instanceof Square works because Square is a class, which exists at run time. s instanceof Shape does not compile: the checker reports error TS2693, "'Shape' only refers to a type, but is being used as a value here".
package main

import (
	"fmt"
	"reflect"
)

type Point struct {
	X int `json:"x"`
	Y int `json:"y"`
}

func (p Point) Sum() int { return p.X + p.Y }

func main() {
	var v any = Point{3, 4}
	t := reflect.TypeOf(v)
	val := reflect.ValueOf(v)
	fmt.Println("type:", t.Name(), "kind:", t.Kind())
	for i := 0; i < t.NumField(); i++ {
		f := t.Field(i)
		fmt.Printf("%s %s tag=%q = %v\n", f.Name, f.Type, f.Tag.Get("json"), val.Field(i))
	}
	out := val.MethodByName("Sum").Call(nil)
	fmt.Println("Sum() =", out[0].Int())
}
Output
type: Point kind: struct
X int tag="x" = 3
Y int tag="y" = 4
Sum() = 7

reflect.TypeOf and reflect.ValueOf take an interface value and return its dynamic type and value. Struct tags, such as json:"x", are strings attached to fields. The language gives them no meaning, and a program reads them through reflection.

This code panics, on purpose.

package main

import (
	"fmt"
	"reflect"
)

type Point struct {
	X, Y int
}

func main() {
	p := Point{3, 4}
	v := reflect.ValueOf(p)
	v.Field(0).SetInt(10)
	fmt.Println(p)
}

ValueOf(p) receives a copy of p, so changing it would change nothing. The reflection value is not settable, and SetInt panics. The compiler accepts the program.

package main

import (
	"fmt"
	"reflect"
)

type Point struct {
	X, Y int
}

func main() {
	p := Point{3, 4}
	v := reflect.ValueOf(&p).Elem()
	fmt.Println("settable:", v.Field(0).CanSet())
	v.Field(0).SetInt(10)
	fmt.Println(p)
}
Output
settable: true
{10 4}

A pointer to p gives a reflection value that refers to p itself. Its exported fields are settable.

  • Verdict: native. The package reflect gives the dynamic type (reflect.Type) and the value (reflect.Value) of any interface value, and it can read and set fields and call methods.
  • Only exported fields are settable. A value is settable only if it refers to the original variable, for example through a pointer.
  • Mistakes in reflective code panic at run time. The compiler sees only calls on reflect.Value.
RustGitHub
use std::any::{Any, type_name};

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn describe(value: &dyn Any) -> String {
    if let Some(p) = value.downcast_ref::<Point>() {
        format!("a Point with x = {} and y = {}", p.x, p.y)
    } else if let Some(n) = value.downcast_ref::<i32>() {
        format!("an i32 equal to {n}")
    } else {
        String::from("a value of an unknown type")
    }
}

fn name_of<T>(_: &T) -> &'static str {
    type_name::<T>()
}

fn main() {
    let p = Point { x: 3, y: 4 };
    println!("{}", describe(&p));
    println!("{}", describe(&7_i32));
    println!("{}", describe(&"text"));
    println!("{}", name_of(&1.5_f64));
    println!("{p:?}");
}
Output
a Point with x = 3 and y = 4
an i32 equal to 7
a value of an unknown type
f64
Point { x: 3, y: 4 }

dyn Any can only answer one question: is this value of the concrete type T? It cannot list the fields of Point or find a method by name. #[derive(Debug)] prints the fields, but the derive macro writes that code at compile time.

  • Verdict: absent. Rust has no run-time reflection of fields or methods. The module std::any gives TypeId, type_name and downcasting of dyn Any to a concrete type.
  • &dyn Any cannot test whether a type implements a trait.
  • Code that needs the structure of a type, such as a serializer, uses a derive macro that generates the code at compile time.
  • Static reflection and code generation. A derive macro or an annotation processor reads the structure of a type at compile time and generates code. The compiler checks the result, and the program needs no metadata at run time. See Syntactic macros and Annotations.
  • Annotations read by reflection. Java annotations with run-time retention and C# attributes are stored in the metadata and read through reflection. Frameworks use them to find the classes and methods they should handle. See Annotations.
  • Dynamic typing. In Python and JavaScript, the ordinary operations already look up names at run time. Reflection there adds the ability to list the names. See Static and dynamic typing.
  • Type erasure. If a language erases the type arguments of generics, reflection sees only the erased types. TypeScript erases all of its types.17 See Type erasure.
  • Dynamic dispatch. A virtual call or an interface call chooses a method at run time, but the compiler has checked that the method exists. Reflection drops that check. See Interfaces and Subtyping.

Pitfalls

Names as strings

A method name passed to getDeclaredMethod, GetMethod, MethodByName or getattr is a string. The compiler does not check it. The Java example typo throws NoSuchMethodException, the C# example typo throws NullReferenceException because GetMethod returned null, and the Python example typo raises AttributeError.614 A rename in an IDE does not change the strings, so code that worked can break after a refactoring. In JavaScript the error does not even stop the program: the example typo gets undefined and computes NaN.

Exceptions in a wrapper

A method called through reflection that throws does not throw its own exception to the caller. Java wraps it in InvocationTargetException, and .NET wraps it in TargetInvocationException.811 A catch for the original type does not catch it. The C# example wrapped shows the inner FormatException.

A copy instead of the original

In Go, reflect.ValueOf(p) reflects a copy of p, so the fields are not settable, and the Set methods panic. Only exported fields are settable at all.2 The Go example not-settable shows the panic.

Depending on the order of members

The Java methods getDeclaredFields and getDeclaredMethods return members in no particular order.6 Code that writes fields in the order that reflection returns them can produce a different format with a different JVM. Sort the members, or use a source with a defined order, such as getRecordComponents.6

Breaking encapsulation

Reflection can read and set private fields where access control allows it. The Java tutorial warns that reflective code "breaks abstractions and therefore may change behavior with upgrades of the platform".5 The Java example private-own sets a private balance to a negative value that the class's own methods would never allow.

Reflection and trimming

A .NET app that is trimmed loses the code that the trimmer does not see used. Code that loads a type by a name read at run time "fundamentally can't be made analyzable", and the SDK marks it with RequiresUnreferencedCodeAttribute.12 The first fix the documentation gives is to remove the reflection and use generics checked at compile time.12 Kotlin keeps its full reflection in a separate library for a similar reason: size.20

Cost

  • Speed. "Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed." Reflective operations are slower, and the Java tutorial says to avoid them in code that runs often.5
  • Static checks. Names, argument counts and argument types are checked when the program runs, not when it is compiled. In Go, a call of SetFloat on a value that is not settable compiles and then panics.2
  • Size. The metadata must be in the program. .NET trimming and the separate kotlin-reflect artifact both trade reflection for a smaller program.1220
  • Clarity. Pike's conclusion: "It's a powerful tool that should be used with care and avoided unless strictly necessary."2 The Java tutorial: "If it is possible to perform an operation without using reflection, then it is preferable to avoid using it."5

History

  • 1982. Brian Cantwell Smith's MIT thesis gave an account of reflection in programming languages, defined procedural reflection, and presented 3-LISP, a Lisp dialect with reflective powers.1
  • Java 1.1. The Java API marks getDeclaredFields, getDeclaredMethods and getDeclaredConstructors of Class with "Since: 1.1".6
  • 2011. Rob Pike published "The Laws of Reflection" for Go.2

References

  1. Brian Cantwell Smith, Procedural Reflection in Programming Languages, Volume I, PhD thesis, MIT, February 1982 (MIT-LCS-TR-272), Abstract, page 2; Extended Abstract, page 3; Prologue, page 17; 1.a General Overview, page 27; page 41
  2. Rob Pike, The Laws of Reflection, The Go Blog, 6 September 2011, the introduction; The first, second and third laws of reflection; Conclusion
  3. Go standard library, package reflect, Overview
  4. The Go Programming Language Specification, Struct types, the paragraph on tags
  5. The Java Tutorials, Trail, The Reflection API, Uses of Reflection; Drawbacks of Reflection
  6. Java SE 25 API, java.lang.Class, getDeclaredFields; getDeclaredMethods; getDeclaredConstructors; getRecordComponents; getDeclaredMethod
  7. Java SE 25 API, java.lang.reflect.AccessibleObject, the class description; setAccessible(boolean)
  8. Java SE 25 API, java.lang.reflect.Method, invoke, Throws
  9. Reflection in .NET, the introduction and the list of classes
  10. Type.GetProperties Method, Remarks
  11. MethodBase.Invoke Method, Exceptions
  12. Fixing trim warnings, Understanding warning categories; Approach 1, Eliminate reflection; RequiresUnreferencedCode
  13. Python documentation, inspect, Inspect live objects, the introduction; inspect.signature
  14. Python documentation, Built-in Functions, getattr
  15. Python documentation, Glossary, type hint
  16. ECMA-262, 16th edition (ECMAScript 2025), 28 Reflection, 28.1 The Reflect Object; 28.1.1 Reflect.apply; 28.1.10 Reflect.ownKeys
  17. The TypeScript Handbook, The Basics, Erased Types
  18. The Rust Standard Library, Module std::any, the module description; Any and TypeId
  19. N4950, Working Draft, Standard for Programming Language C++ (the C++23 draft), 7.6.1.8 [expr.typeid], paragraphs 1, 3 and 4; 17.7.3 [type.info], name, paragraph 8
  20. Kotlin documentation, Reflection, the introduction; JVM dependency; Class references
  21. PowerShell documentation, Get-Member, Description
  22. PostgreSQL documentation, The Information Schema, the first paragraph

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/7Q4RFY/text.yaml