Sub topic 1
What reflection is and when to use it
Reflection is the part of the Java platform that lets a running program examine its own types and act on them. With it you can ask a class for its name, list its methods, create an instance whose class you only know as a string, or call a method chosen at runtime. This chapter explains the working model, shows the first few calls, and sets out when reflection is the right tool and when it is not. The later chapters cover each part of the API in detail.
Prerequisites
This chapter assumes you already know:
- 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.
You do not need any prior knowledge of annotations, class loaders, or the module system. Later chapters introduce them as needed.
The working model
Normally the compiler fixes everything about a call. When you write s.length(), the compiler checks that s has a length() method and records the call in the class file. If the method does not exist, the program does not compile.
Reflection moves that decision to runtime. The JVM keeps a description of every loaded type in a java.lang.Class object. The reflection API, mostly in java.lang.reflect, reads those descriptions and lets you act on them. The descriptions are made of ordinary objects:
Classrepresents a type.Fieldrepresents a field.Methodrepresents a method.Constructorrepresents a constructor.Modifierdecodes flags such aspublic,static, andfinal.
The key point is that these objects describe code. Your program can read them, pass them around, and use them to operate on other objects.
A first example: a class chosen at runtime
The program below takes a class name as a string. The compiler has no way to know which class it will be.
public class FirstReflection {
public static void main(String[] args) throws Exception {
String className = args.length > 0 ? args[0] : "java.util.ArrayList";
Class<?> type = Class.forName(className);
Object instance = type.getDeclaredConstructor().newInstance();
System.out.println("Created a " + instance.getClass().getName());
System.out.println("Its value prints as: " + instance);
}
}Run with no arguments, it prints Created a java.util.ArrayList and Its value prints as: []. Run it with java.util.HashSet as the argument and it creates a HashSet instead. Nothing was recompiled. The name is only data until the JVM resolves it.
This is the core use of reflection. It lets a program work with types it did not know about when it was written.
Direct calls versus reflective calls
Here is the same operation done both ways.
import java.lang.reflect.Method;
public class DirectVsReflective {
public static void main(String[] args) throws Exception {
String s = "reflection";
System.out.println(s.toUpperCase());
Method m = String.class.getMethod("toUpperCase");
System.out.println(m.invoke(s));
}
}Both lines print REFLECTION. The two versions differ in what the compiler checks:
| Aspect | Direct call | Reflective call |
|---|---|---|
| Method name | Checked by the compiler | A string, checked only at runtime |
| Argument types | Checked by the compiler | Passed as `Object`, checked at runtime |
| Return type | Known statically | Returned as `Object`, needs a cast |
| Checked exceptions | Only those the method declares | Several reflection exceptions to handle |
| Speed | Fast, can be inlined | Slower, covered in a later chapter |
If you misspell the name as "toUppercase", the direct version fails to compile. The reflective version compiles and then throws NoSuchMethodException when it runs. You give up compile-time safety in exchange for flexibility.
Reading structure you did not write code for
Reflection can also treat an object as data. The next program prints the instance fields of any object, which is a simplified version of what debuggers and serialization libraries do.
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
class Point {
int x = 3;
int y = 4;
static int created = 0;
}
public class Dump {
static String dump(Object target) throws IllegalAccessException {
StringBuilder sb = new StringBuilder(target.getClass().getSimpleName());
sb.append('{');
boolean first = true;
for (Field f : target.getClass().getDeclaredFields()) {
if (Modifier.isStatic(f.getModifiers())) {
continue;
}
f.setAccessible(true);
if (!first) {
sb.append(", ");
}
sb.append(f.getName()).append('=').append(f.get(target));
first = false;
}
return sb.append('}').toString();
}
public static void main(String[] args) throws Exception {
System.out.println(dump(new Point()));
}
}The output is Point{x=3, y=4}. The dump method works for any class, and you never write a per-class toString. This is the main benefit of reflection: one piece of generic code handles many types.
Three calls in this program deserve a note now. getDeclaredFields() returns every field declared in the class, including private ones. Modifier.isStatic decodes the field's flags. setAccessible(true) asks the JVM to skip the normal access check. That last call is powerful and has limits, and a later chapter covers it.
Where reflection is used
You rarely write reflection-heavy code in everyday application logic, but you depend on it constantly:
- Dependency injection containers find constructors and annotated fields, then build and wire objects.
- Serialization libraries such as JSON mappers read an object's fields to write them out, and set fields when reading data back.
- Test frameworks discover methods marked as tests and call them.
- Object-relational mappers map fields to table columns.
- Plugin systems load a class named in a configuration file.
- IDEs, debuggers, and profilers inspect objects they have never seen.
All of these share one trait. The code doing the work is written once, ahead of time, and the types it works on arrive later.
When to use reflection, and when not to
Reflection is a good fit when all of these are true:
- The set of types is not known at compile time, or is too large to handle by hand.
- The code is generic infrastructure, such as a framework, a tool, or a library.
- A cleaner, type-safe alternative is not available.
Prefer something else when you know the types. In that case, an interface, a lambda, or an ordinary method call is shorter, faster, and checked by the compiler. If you find yourself calling getMethod("save") on a class you control, add save() to an interface instead.
The costs are real:
- Lost compile-time checks. Renaming a method does not update strings that refer to it. The failure shows up at runtime.
- Slower execution. Reflective calls do extra checks and are harder for the JIT compiler to optimize.
- Weaker encapsulation. Reading private fields breaks the guarantees a class author intended.
- Platform limits. Since Java 9, the module system can block access to internals, and tools such as obfuscators and native-image compilers can rename or remove the members your strings point to.
- Harder code to read. Generic code that passes
Objectaround hides what the program actually does.
What comes next
The following chapters build the API step by step. You will obtain Class objects in several ways, inspect fields, methods, and constructors, create objects and invoke members, and learn how setAccessible interacts with modules. Then you will define annotations, read them at runtime, and use them to build a small validator. The tutorial finishes with dynamic proxies, method handles, performance costs, and compile-time annotation processing.
Exercise
A teammate writes Method m = Account.class.getMethod("getBalence"); (misspelled). When is the error reported, and what type of error is it? How would a direct call account.getBalence() differ?
Show answer
The reflective version compiles, because the method name is only a string. The error is reported at runtime, when getMethod throws a NoSuchMethodException. The direct call account.getBalence() fails at compile time with a "cannot find symbol" error, so the mistake is caught before the program runs.
Exercise
You are writing a class that must call close() on a Connection object you define yourself. Should you use reflection? If not, what should you use instead?
Show answer
No. The type is known at compile time, so reflection only adds runtime risk and cost. Call connection.close() directly, or make the type implement AutoCloseable and use try-with-resources. Reflection is for code that cannot name the type in advance.
Exercise
In the Dump example, why does the loop skip fields where Modifier.isStatic is true?
Show answer
Static fields belong to the class, not to the instance being described. Skipping them keeps the output to the object's own state, so Point{x=3, y=4} does not include created.