What Is Reflection?

Reflection is a programming capability that allows a program to inspect, analyze, and modify its own structure and behavior at runtime. This includes examining classes, methods, fields, and other metadata — and in many languages, even dynamically invoking or modifying them.

Reflection is like giving a program the ability to “look in a mirror” and act on what it sees.

It is widely used in object-oriented and dynamic languages for:

  • Dependency injection
  • Testing
  • Serialization
  • Framework development
  • Metaprogramming

1. Why Use Reflection?

Use CasePurpose
Debugging ToolsIntrospect variables and call stacks
Serialization LibrariesAccess private fields, nested structures
Dependency InjectionLoad classes and inject objects at runtime
ORM FrameworksMap object fields to database tables
Test AutomationDiscover and invoke test methods dynamically

2. Reflection in Java

Java has a powerful reflection API in the java.lang.reflect package.

Basic Example:

import java.lang.reflect.*;

public class Demo {
    public String greet(String name) {
        return "Hello, " + name;
    }
}

Class clazz = Demo.class;
Method method = clazz.getMethod("greet", String.class);
String result = (String) method.invoke(new Demo(), "Alice");

System.out.println(result);  // Hello, Alice

Reflection Capabilities in Java:

FeatureAPI Example
Inspect class nameclazz.getName()
List fieldsclazz.getDeclaredFields()
Invoke methodmethod.invoke(obj, args)
Access private fieldfield.setAccessible(true)

3. Reflection in Python

Python offers reflection through its built-in functions and modules like getattr, setattr, and inspect.

Example:

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hi, I’m {self.name}"

p = Person("Alice")

# Access attribute dynamically
print(getattr(p, 'name'))      # Alice

# Call method by name
print(getattr(p, 'greet')())   # Hi, I’m Alice

Python also allows:

  • Checking types (type, isinstance)
  • Getting class hierarchy (__bases__)
  • Listing members (dir, vars)
  • Full introspection via inspect module

4. Reflection in C#

C# provides reflection via the System.Reflection namespace.

Example:

Type type = typeof(MyClass);
MethodInfo method = type.GetMethod("Greet");
object result = method.Invoke(new MyClass(), new object[] { "Alice" });
Console.WriteLine(result);

Reflection in C# allows access to:

  • Metadata (attributes, names)
  • Runtime method invocation
  • Constructor discovery
  • Assembly loading

5. Reflection in JavaScript

JavaScript has dynamic typing, so many reflection-like capabilities are native.

Examples:

const obj = {
  name: "Alice",
  greet() { return `Hi, ${this.name}` }
};

console.log(obj["name"]);           // Alice
console.log(obj["greet"]());        // Hi, Alice

With ES6+ and Reflect API:

Reflect.set(obj, 'name', 'Bob');
console.log(Reflect.get(obj, 'name'));  // Bob

6. Common Capabilities of Reflection

OperationDescription
Inspect class nameView the name or type of the object
Enumerate methodsList available methods or functions
Read/write fieldsGet or set instance variables dynamically
Call methodsInvoke functions with arguments
Check typesRuntime type checking
Create objectsInstantiate a class dynamically
Analyze decoratorsRead annotations or attributes

7. Reflection vs Introspection

ConceptDescription
ReflectionAbility to inspect and modify code structures at runtime
IntrospectionAbility to inspect but not modify structures (read-only)

Languages like Python support both, whereas some like Go or Rust support introspection with limited reflection.

8. Performance Considerations

Reflection can be significantly slower than direct method or field access because:

  • It bypasses optimizations
  • It may require extra safety checks
  • It often works with generic objects (type erasure)

Best Practices:

  • Avoid reflection in performance-critical paths
  • Cache reflective lookups if repeated
  • Consider alternatives like code generation or decorators

9. Security Considerations

Improper use of reflection can lead to:

  • Security vulnerabilities (e.g., accessing private fields)
  • Sandbox violations in restricted environments
  • Code injection if external strings are used as method/field names

Tips:

  • Never use untrusted input directly in reflection
  • Validate class and method names carefully
  • Respect encapsulation rules unless necessary

10. Use Cases in Frameworks

Framework / LibraryUse of Reflection
Spring (Java)Dependency injection, bean discovery
HibernateMapping Java classes to DB schemas
Django (Python)Model inspection, admin interface
.NET CoreAttribute-based configuration
Angular (JS/TS)Component metadata parsing
Jest / PytestTest discovery and dynamic execution

Reflection is often essential to frameworks that require generic extensibility and configuration by convention.

11. Limitations

LimitationImpact
Runtime-onlyNo compile-time safety
Hard to debugErrors may be raised at runtime only
Performance overheadSlower than direct access
Complex syntaxEspecially in statically typed languages
Limited in some languagese.g., Go restricts reflective access to private fields

12. Alternatives to Reflection

TechniqueWhen to Use
Code GenerationWhen performance matters and types are known ahead
Dependency InjectionWith pre-wired configurations or registries
Decorator PatternsFor extending behavior with less dynamism
Switch-based DispatchWhere full reflection is overkill

13. Summary

FeatureDescription
What it isRuntime inspection and manipulation of code structures
Main usesTesting, serialization, dependency injection, dynamic invocation
LanguagesJava, Python, C#, JavaScript, Ruby
RisksPerformance, security, complexity
Common APIsjava.lang.reflect, inspect, System.Reflection, Reflect

Reflection enables flexible, powerful code — but like a mirror, it should be used carefully to avoid distorting what’s being reflected.

Related Keywords

  • Introspection
  • Runtime Inspection
  • Metadata
  • Dynamic Typing
  • Method Invocation
  • Object Introspection
  • Type Discovery
  • Code Generation
  • Decorator Pattern
  • Annotations
  • Proxy Object
  • Dependency Injection
  • Java Reflection API
  • Python inspect
  • C# Reflection
  • JavaScript Reflect
  • Serialization
  • Testing Frameworks
  • Attribute Parsing
  • Dynamic Dispatch