Advanced Topic 54 of 54 Programming Fundamentals
Reflection
Examining and modifying a program's own structure while it runs.
How it works
Reflection lets a program inspect its own types, fields and methods at runtime and even call them by name, using metadata that the runtime keeps about every class. A program can discover what an object offers, create instances from names and read annotations. It supports flexible, data-driven designs at the cost of static guarantees.
Step-by-step walkthrough
- A running program asks about its own structure.
- It lists the fields and methods of an object.
- It finds a method by a name string.
- It invokes that method dynamically.
- Frameworks use this for serialization and dependency injection.
Where it is used
Serialization libraries, dependency injection containers, test frameworks that discover test methods, object-relational mappers, IDE tooling and plug-in loaders use reflection. It makes generic code possible when types are unknown at compile time.
Common pitfall
Reflection bypasses compile-time checking, so errors appear only at run time, it is slower than direct calls and it can break encapsulation by reaching into private members. Refactoring tools may miss string-based references. Use it at framework boundaries and prefer ordinary polymorphism in application code.
Where it fits in the course
Reflection is topic 54 of 54 in Programming Fundamentals, rated Advanced. It follows Metaprogramming. It is the last topic in this area.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Reflection?
Where do people use Reflection?
What is the most common mistake with Reflection?
What should I learn before this topic?
How can I practice it?
Is Reflection hard to learn?
How long does it take to learn Reflection?
Which topics are related to Reflection?
What should I study after Reflection?
Related topics
- Metaprogramming (Programming Fundamentals)
- Memoization (Programming Fundamentals)
- Monads (Programming Fundamentals)
- Currying and Partial Application (Programming Fundamentals)