Reflection
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
inspect and invoke code at runtime.
Planned topics
Class<?>gives fields, methods, constructors, annotations, and modifiers.- Invoke with
Method.invoke; read fields withField.get(needssetAccessible(true)for private members, and may be blocked by modules). - Frameworks use it for dependency injection, serialization, and mapping.
- Costs: slower than direct calls, bypasses compile-time checks, and can break encapsulation.
- Avoid in hot paths; cache
Methodobjects or useMethodHandle.
Draft outline details
Demonstration
for (Method m : Product.class.getDeclaredMethods()) {
System.out.println(m.getName() + " " + m.getReturnType());
}Check your understanding
Why avoid reflection in hot loops?
Show answer
Slower, and checks move from compile time to runtime.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.