Sub topic 1
What reflection is and when to use it
Prerequisites
This chapter assumes you know the following:
- Core Java syntax: classes, interfaces, methods, fields, and constructors.
- Basic generics and collections.
- Checked exceptions and try/catch.
- How to compile and run a Java program from the command line or an IDE.
What reflection is
Reflection is the ability of a running Java program to examine its own types and to act on them. Normally you write list.add("x"), and the compiler checks that add exists. With reflection you can instead ask at runtime, "What methods does this class have?" and then call one by name.
The JVM makes this possible by keeping a description of every loaded type. That description is an instance of java.lang.Class. The java.lang.reflect package then provides types such as Field, Method, and Constructor that let you look inside a Class.
A first look
The program below receives a class name as text. The compiler cannot know the name, so reflection is the only way to work with it. The program loads the class, counts its public methods, and creates an instance.
public class WhatIsReflection {
public static void main(String[] args) throws Exception {
String className = args.length > 0 ? args[0] : "java.util.ArrayList";
Class<?> type = Class.forName(className);
System.out.println("Loaded: " + type.getName());
System.out.println("Public methods: " + type.getMethods().length);
Object instance = type.getDeclaredConstructor().newInstance();
System.out.println("Created: " + instance);
}
}With the default name it prints Loaded: java.util.ArrayList, a method count that depends on your Java version, and Created: []. If you pass a class that has no public no-argument constructor, newInstance() throws an exception. Reflection moves many errors from compile time to runtime.
When to use it
Reflection fits code that must work with types it did not know about when it was compiled. Typical cases:
- Frameworks that discover and wire up your classes, such as dependency injection and serialization libraries.
- Tools that map objects to other formats, such as JSON, XML, or database rows.
- Test runners that find methods marked as tests and call them.
- Plugin systems that load a class named in a configuration file.
When to avoid it
For ordinary application code, a direct call is better. The table shows why.
| Concern | Direct call | Reflection |
|---|---|---|
| Type checking | At compile time | At runtime |
| Refactoring | Tools rename safely | Names in strings can break silently |
| Speed | Fast, easy for the JIT to optimize | Slower, with extra checks |
| Encapsulation | Respected | Can reach private members |
If you know the type when you write the code, use a normal call or an interface. Reach for reflection only when the type is unknown until runtime.
The next chapters build on this overview. You will obtain Class objects in several ways, inspect their members, and then use annotations to attach metadata that reflection can read.
Exercise
A configuration file contains the text "com.example.ReportPlugin". Why does your program need reflection to run that plugin, and why would you not use reflection to call a method on a String you already hold in a variable?
Show answer
The class name is only known at runtime, so the compiler cannot check or link it. Class.forName can load it from the text. For a String variable the type is known at compile time. A direct call such as s.length() is type checked, faster, and safe to refactor, so reflection adds cost and risk for no benefit.