Reflection
Reflection API, inspecting classes at runtime, dynamic method invocation
- Understand what reflection is and when to use it
- Inspect class metadata, fields, methods, and constructors at runtime
- Invoke methods and access fields dynamically
- Understand the performance implications of reflection
Part of the Concept and Coding Java lecture series. These notes are fully self-contained — no prior lecture viewing is required. This chapter covers Java Reflection in depth: what it is, how it works internally, how to reflect classes / methods / fields / constructors, invoking private members, and why reflection is dangerous and slow.
Table of Contents
- What is Reflection?
- The
ClassObject — Foundation of Reflection - Three Ways to Get a Class Object
- Reflecting a Class
- Reflecting Methods
- Invoking a Method via Reflection
- Reflecting Fields
- Changing Field Values via Reflection
- Reflecting Constructors
- How Reflection Breaks Singleton
- getFields vs getDeclaredFields — The Difference
- Why Reflection Should Be Avoided
- When Reflection IS Used
- Mermaid Diagrams
- Quick-Reference Tables
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary Cheat Sheet
1. What is Reflection?
Overview
Reflection is a powerful and advanced feature of Java that allows a program to examine and modify itself at runtime. With reflection, you can look inside any class, discover its methods, fields, and constructors, and even invoke them — all while the program is running, without knowing the class at compile time.
Real-World Analogy
Imagine a doctor performing an X-ray on a patient. The patient doesn't need to do anything differently. The X-ray machine (reflection) looks inside the body (class) and reveals its internal structure — bones, organs, sizes — without the patient's active cooperation. The doctor can then act on what they find.
Reflection does the same for Java classes. It peeks inside them at runtime and exposes their internal structure.
Formal Definition
Java Reflection
is an API (java.lang.reflect package) that allows a program to inspect and manipulate the internal structure of classes, interfaces, methods, fields, and constructors at runtime, even if they are private.
What Reflection Can Do
| Capability | Description |
|---|---|
| Inspect a class | Get class name, modifier, interfaces implemented |
| Inspect methods | Get method names, return types, parameters, modifiers |
| Inspect fields | Get field names, types, modifiers |
| Inspect constructors | Get constructor parameters and modifiers |
| Invoke methods | Call any method (including private) at runtime |
| Change field values | Set any field (including private) at runtime |
| Create objects | Call any constructor (including private) at runtime |
Package Location
All reflection classes live in java.lang.reflect:
1import java.lang.reflect.Method;2import java.lang.reflect.Field;3import java.lang.reflect.Constructor;4import java.lang.reflect.Modifier;The Class class itself lives in java.lang (no import needed).
2. The `Class` Object Foundation of Reflection
What is the `Class` Class?
Before you can reflect anything, you need to understand java.lang.Class. This is a special class whose name is literally Class — and it is the entry point for all reflection.
Every Java class, when loaded by the JVM, gets an associatedClassobject automatically. ThisClassobject holds all the metadata about that class — its name, modifier, methods, fields, constructors, superclass, and implemented interfaces.
Who Creates Class Objects?
The JVM creates them — not you.
When the JVM loads a class (e.g., Bird), it:
- Reads the compiled
.classbytecode file. - Creates an instance of
java.lang.Classinternally. - Populates that
Classinstance with metadata aboutBird.
You can then retrieve this pre-created Class object using one of three methods (Section 3).
What Metadata Does a Class Object Hold?
1Class Object for "Eagle"2┌────────────────────────────────────────────┐3│ getName() → "Eagle" │4│ getModifiers() → public │5│ getMethods() → [fly, eat, ...] │6│ getFields() → [breed, ...] │7│ getConstructors() → [Eagle()] │8│ getSuperclass() → Object │9│ getInterfaces() → [Flyable, ...] │10└────────────────────────────────────────────┘How Many Class Objects Exist?
Exactly one per class, per JVM instance. If Bird is loaded once, there is exactly one Class object for Bird. Even if you create 100 Bird objects, they all share the same single Class object.
3. Three Ways to Get a Class Object
The JVM creates Class objects; you only need to retrieve them. There are three ways:
Method 1 `Class.forName(String className)`
Pass the fully qualified class name as a String. This is useful when you don't have the class available at compile time (the most dynamic approach).
1Class<?> eagleClass = Class.forName("Eagle");2// or with full package path:3Class<?> listClass = Class.forName("java.util.ArrayList");Class.forName() throws a checked exception ClassNotFoundException if the class name is wrong or the class cannot be found on the classpath. Always handle it.1try {2 Class<?> eagleClass = Class.forName("Eagle");3} catch (ClassNotFoundException e) {4 e.printStackTrace();5}Method 2 `.class` Literal
If you have access to the class type at compile time, use the .class literal directly on the class name. This is the safest and most readable approach.
1Class<Eagle> eagleClass = Eagle.class;2Class<Integer> intClass = Integer.class;3Class<String> strClass = String.class;No exception handling required — this is resolved at compile time.
Method 3 `object.getClass()`
If you already have an instance of the class, call getClass() on it. This is inherited from java.lang.Object, so every Java object has this method.
1Eagle eagle = new Eagle();2Class<?> eagleClass = eagle.getClass();This is useful when you receive an object of unknown type and want to inspect it dynamically.
Side-by-Side Comparison
| Method | Syntax | Compile-time class needed? | Exception? | Best Used When |
|---|---|---|---|---|
Class.forName() | Class.forName("Eagle") | ❌ No — string only | ✅ Yes — ClassNotFoundException | Class name known only at runtime (plugins, frameworks) |
.class literal | Eagle.class | ✅ Yes | ❌ No | Class known at compile time |
getClass() | obj.getClass() | ✅ Yes (object exists) | ❌ No | You already have an instance |
4. Reflecting a Class
The Subject Class
Throughout all examples, we will use this simple class:
1public class Eagle {2 public String breed; // public field3 private boolean canSwim; // private field4
5 public void fly() {6 System.out.println("Eagle is flying.");7 }8
9 private void eat() {10 System.out.println("Eagle is eating.");11 }12}Getting Basic Class Metadata
1import java.lang.reflect.Modifier;2
3public class ReflectClass {4 public static void main(String[] args) {5 // Step 1: Get the Class object6 Class<Eagle> eagleClass = Eagle.class;7
8 // Step 2: Fetch metadata9 System.out.println("Class name: " + eagleClass.getName());10 System.out.println("Simple name: " + eagleClass.getSimpleName());11 System.out.println("Modifier: " + Modifier.toString(eagleClass.getModifiers()));12 System.out.println("Superclass: " + eagleClass.getSuperclass().getName());13 System.out.println("Package: " + eagleClass.getPackageName());14 }15}Class name: Eagle Simple name: Eagle Modifier: public Superclass: java.lang.Object Package: (default package)
Line-by-Line Explanation
| Line | What It Does |
|---|---|
Eagle.class | Retrieves the JVM-created Class object for Eagle |
getName() | Returns the fully qualified class name |
getSimpleName() | Returns just the class name without the package |
getModifiers() | Returns an int encoding the modifier; Modifier.toString() converts it to readable text |
getSuperclass() | Returns the Class object of the parent class (Object here) |
Useful Class-Level Methods
| Method | Returns | Example Output |
|---|---|---|
getName() | Fully qualified class name | "com.example.Eagle" |
getSimpleName() | Class name only | "Eagle" |
getModifiers() | int modifier code | Use Modifier.toString() to read |
getSuperclass() | Parent Class object | java.lang.Object |
getInterfaces() | Array of implemented interfaces | [Flyable, ...] |
getPackageName() | Package name | "com.example" |
isInterface() | boolean | false |
isAbstract() | boolean (via Modifier) | false |
getDeclaredClasses() | Nested classes | array |
5. Reflecting Methods
Getting All PUBLIC Methods `getMethods()`
getMethods() returns all public methods of the class and all its superclasses (including Object).
1import java.lang.reflect.Method;2
3public class ReflectMethods {4 public static void main(String[] args) {5 Class<Eagle> eagleClass = Eagle.class;6
7 Method[] methods = eagleClass.getMethods(); // public only, including inherited8
9 for (Method method : methods) {10 System.out.println("Method: " + method.getName());11 System.out.println("Return Type: " + method.getReturnType());12 System.out.println("Declared in: " + method.getDeclaringClass());13 System.out.println("---");14 }15 }16}Method: fly Return Type: void Declared in: class Eagle --- Method: wait Return Type: void Declared in: class java.lang.Object --- Method: notify Return Type: void Declared in: class java.lang.Object --- ... (other Object methods)
getMethods() also returns inherited methods from Object (like wait, notify, equals, toString). This is because every Java class implicitly extends Object.Getting ALL Methods (Including Private) `getDeclaredMethods()`
getDeclaredMethods() returns all methods declared directly in that class — both public and private — but does not include inherited methods from parent classes.
1import java.lang.reflect.Method;2import java.lang.reflect.Modifier;3
4public class ReflectDeclaredMethods {5 public static void main(String[] args) {6 Class<Eagle> eagleClass = Eagle.class;7
8 Method[] methods = eagleClass.getDeclaredMethods(); // all in Eagle, no Object methods9
10 for (Method method : methods) {11 System.out.println("Method: " + method.getName());12 System.out.println("Modifier: " + Modifier.toString(method.getModifiers()));13 System.out.println("Return Type: " + method.getReturnType());14 System.out.println("---");15 }16 }17}Method: fly Modifier: public Return Type: void --- Method: eat Modifier: private Return Type: void ---
Both fly (public) and eat (private) appear — but wait, notify, etc. from Object do not.
Method Metadata All Available Get Methods
Once you have a Method object, you can extract:
| Method | Returns |
|---|---|
getName() | Method name ("fly") |
getReturnType() | Return type (void, int, etc.) |
getParameterTypes() | Array of parameter types |
getParameterCount() | Number of parameters |
getModifiers() | Modifier int (use Modifier.toString()) |
getDeclaringClass() | The class in which this method is declared |
getExceptionTypes() | Exceptions the method declares it throws |
getAnnotations() | Annotations on the method |
getMethods() vs getDeclaredMethods()
| Feature | getMethods() | getDeclaredMethods() |
|---|---|---|
| Access scope | public only | All — public + private + protected + default |
| Inherited methods? | ✅ Yes — includes Object methods | ❌ No — current class only |
| Private methods? | ❌ No | ✅ Yes |
| Use when | You want all publicly accessible behavior | You want to inspect exactly what this class defines |
6. Invoking a Method via Reflection
Reflection doesn't just let you read metadata — you can also call methods at runtime.
The Subject Class
1public class Eagle {2 public void fly(int speed, boolean gliding, String direction) {3 System.out.println("Flying at speed " + speed +4 ", gliding=" + gliding +5 ", direction=" + direction);6 }7}Step-by-Step Invocation
1import java.lang.reflect.Constructor;2import java.lang.reflect.Method;3
4public class InvokeMethodReflection {5 public static void main(String[] args) throws Exception {6
7 // Step 1: Get the Class object8 Class<?> eagleClass = Class.forName("Eagle");9
10 // Step 2: Create an instance of Eagle using reflection11 Object eagleInstance = eagleClass.getDeclaredConstructor().newInstance();12
13 // Step 3: Get the specific method by name and parameter types14 Method flyMethod = eagleClass.getMethod("fly",15 int.class, boolean.class, String.class);16
17 // Step 4: Invoke the method on the instance, passing arguments18 flyMethod.invoke(eagleInstance, 120, true, "North");19 }20}Flying at speed 120, gliding=true, direction=North
Step-by-Step Explanation
| Step | Code | What Happens |
|---|---|---|
| 1 | Class.forName("Eagle") | Retrieves the JVM Class object for Eagle |
| 2 | getDeclaredConstructor().newInstance() | Calls the no-arg constructor, creates an Eagle object |
| 3 | getMethod("fly", int.class, boolean.class, String.class) | Finds the method named fly with exactly these three parameter types |
| 4 | flyMethod.invoke(eagleInstance, 120, true, "North") | Calls eagleInstance.fly(120, true, "North") |
invoke(object, args...) takes the object on which to call the method as the first argument, followed by the actual method arguments. For static methods, pass null as the first argument.Invoking a Private Method
To invoke a private method, you must use getDeclaredMethod() (not getMethod()) and call setAccessible(true):
1Method eatMethod = eagleClass.getDeclaredMethod("eat");2eatMethod.setAccessible(true); // bypass private access restriction3eatMethod.invoke(eagleInstance);setAccessible(true) bypasses Java's access control. This breaks encapsulation and should be used with extreme caution.7. Reflecting Fields
Getting All PUBLIC Fields `getFields()`
Returns all public fields of the class and its superclasses.
1import java.lang.reflect.Field;2
3public class ReflectFields {4 public static void main(String[] args) {5 Class<Eagle> eagleClass = Eagle.class;6
7 Field[] fields = eagleClass.getFields(); // public only8
9 for (Field field : fields) {10 System.out.println("Field name: " + field.getName());11 System.out.println("Field type: " + field.getType());12 System.out.println("Modifier: " +13 java.lang.reflect.Modifier.toString(field.getModifiers()));14 System.out.println("---");15 }16 }17}Field name: breed Field type: class java.lang.String Modifier: public ---
Only breed appears — canSwim is private and is excluded.
Getting ALL Fields `getDeclaredFields()`
Returns all fields in the class (public and private), but not inherited ones.
1Field[] allFields = eagleClass.getDeclaredFields();2
3for (Field field : allFields) {4 System.out.println(field.getName() + " | " +5 field.getType().getSimpleName() + " | " +6 Modifier.toString(field.getModifiers()));7}breed | String | public canSwim | boolean | private
Both fields appear now.
Field Metadata Available Methods
| Method | Returns |
|---|---|
getName() | Field name ("breed") |
getType() | Field type (String, boolean, etc.) |
getModifiers() | Modifier int |
get(object) | Current value of the field on that object |
set(object, value) | Sets the value of the field on that object |
isAccessible() | Whether access override is set |
8. Changing Field Values via Reflection
Setting a Public Field
1import java.lang.reflect.Field;2
3public class SetPublicField {4 public static void main(String[] args) throws Exception {5 Class<Eagle> eagleClass = Eagle.class;6
7 // Get the specific field by name8 Field breedField = eagleClass.getDeclaredField("breed");9
10 // Create an Eagle instance11 Eagle eagleInstance = (Eagle) eagleClass.getDeclaredConstructor().newInstance();12
13 // Set the value14 breedField.set(eagleInstance, "Golden Eagle");15
16 // Verify by reading the field directly17 System.out.println("Breed: " + eagleInstance.breed);18 }19}Breed: Golden Eagle
Setting a Private Field The setAccessible Hack
Trying to set a private field without setAccessible(true) throws an exception:
1Field canSwimField = eagleClass.getDeclaredField("canSwim");2canSwimField.set(eagleInstance, true);3// ❌ throws: IllegalAccessException4// "class Main cannot access a member of class Eagle with modifiers 'private'"Fix — use setAccessible(true):
1import java.lang.reflect.Field;2
3public class SetPrivateField {4 public static void main(String[] args) throws Exception {5 Class<Eagle> eagleClass = Eagle.class;6
7 Field canSwimField = eagleClass.getDeclaredField("canSwim");8
9 // ⚠️ This bypasses the private access restriction10 canSwimField.setAccessible(true);11
12 Eagle eagleInstance = (Eagle) eagleClass.getDeclaredConstructor().newInstance();13
14 // Now we can set the private field15 canSwimField.set(eagleInstance, true);16
17 // Read it back18 System.out.println("Can Swim: " + canSwimField.get(eagleInstance));19 }20}Can Swim: true
What `setAccessible(true)` Does Internally
Normally, Java's access control checks whether the calling class has permission to access a field (based on public/private/protected). When you call setAccessible(true), you instruct the JVM to bypass this check for that specific Field, Method, or Constructor object. It does not actually change the modifier in the class — it just suppresses the runtime check.
setAccessible(true) is a serious breach of encapsulation. It allows any class to read or modify private state of any other class. This is one of the primary reasons reflection is discouraged in production code.Complete Field Reflection Flowchart
9. Reflecting Constructors
The Subject Class
1public class Eagle {2 private Eagle() { // private constructor3 System.out.println("Eagle created via private constructor.");4 }5
6 public void fly() {7 System.out.println("Eagle is flying.");8 }9}Since the constructor is private, you normally cannot create an Eagle object:
1Eagle e = new Eagle(); // ❌ COMPILE ERROR — Eagle() has private accessInspecting Constructors via Reflection
1import java.lang.reflect.Constructor;2import java.lang.reflect.Modifier;3
4public class ReflectConstructor {5 public static void main(String[] args) throws Exception {6 Class<Eagle> eagleClass = Eagle.class;7
8 Constructor<?>[] constructors = eagleClass.getDeclaredConstructors();9
10 for (Constructor<?> constructor : constructors) {11 System.out.println("Constructor: " + constructor.getName());12 System.out.println("Modifier: " + Modifier.toString(constructor.getModifiers()));13 System.out.println("Parameter count: " + constructor.getParameterCount());14 }15 }16}Constructor: Eagle Modifier: private Parameter count: 0
Invoking a Private Constructor via Reflection
1import java.lang.reflect.Constructor;2
3public class InvokePrivateConstructor {4 public static void main(String[] args) throws Exception {5 Class<Eagle> eagleClass = Eagle.class;6
7 // Get the private no-arg constructor8 Constructor<Eagle> constructor = eagleClass.getDeclaredConstructor();9
10 // Bypass private access restriction11 constructor.setAccessible(true);12
13 // Call the private constructor — creates a new Eagle object!14 Eagle eagle = constructor.newInstance();15
16 // Call a method on the illegally created object17 eagle.fly();18 }19}Eagle created via private constructor. Eagle is flying.
Even though Eagle()'s constructor is private, reflection bypasses all access rules and creates the object anyway.
10. How Reflection Breaks Singleton
Background What is Singleton?
The Singleton pattern ensures that only one instance of a class ever exists. It is implemented using:
- A
privateconstructor (prevents external instantiation vianew) - A
staticmethod that controls access to the single instance
1public class Singleton {2 private static Singleton instance;3
4 private Singleton() { } // private — no one can call 'new Singleton()'5
6 public static Singleton getInstance() {7 if (instance == null) {8 instance = new Singleton();9 }10 return instance;11 }12}How Reflection Destroys Singleton
1import java.lang.reflect.Constructor;2
3public class BreakSingleton {4 public static void main(String[] args) throws Exception {5 // Normal way — gets the single instance6 Singleton s1 = Singleton.getInstance();7
8 // Reflection way — creates a SECOND instance illegally9 Class<Singleton> singletonClass = Singleton.class;10 Constructor<Singleton> constructor = singletonClass.getDeclaredConstructor();11 constructor.setAccessible(true); // bypass private12 Singleton s2 = constructor.newInstance(); // second object!13
14 System.out.println("s1 == s2: " + (s1 == s2)); // false — two objects!15 System.out.println("s1 hash: " + s1.hashCode());16 System.out.println("s2 hash: " + s2.hashCode());17 }18}s1 == s2: false s1 hash: 1829164700 s2 hash: 2018699554
Two different objects now exist — Singleton is broken.
How to Protect Singleton from Reflection
Add a guard inside the constructor — if an instance already exists and someone tries to call the constructor again, throw an exception:
1public class Singleton {2 private static Singleton instance;3
4 private Singleton() {5 // Guard against reflection attacks6 if (instance != null) {7 throw new RuntimeException(8 "Use getInstance() — reflection-based instantiation is not allowed.");9 }10 }11
12 public static Singleton getInstance() {13 if (instance == null) {14 instance = new Singleton();15 }16 return instance;17 }18}Now if reflection tries to call the private constructor after the first instance exists:
1Singleton s1 = Singleton.getInstance(); // ✅ works fine2Singleton s2 = constructor.newInstance(); // ❌ throws RuntimeExceptionjava
public enum Singleton {
INSTANCE;
public void doSomething() { ... }
}
`
Java guarantees that enum instances cannot be created via reflection (newInstance() throws an IllegalArgumentException` for enums).11. getFields vs getDeclaredFields The Difference
This distinction applies equally to getMethods/getDeclaredMethods and getConstructors/getDeclaredConstructors.
The Rule
| Method | Scope | Access Level Returned |
|---|---|---|
getFields() | Class + all superclasses | public only |
getDeclaredFields() | This class only | public + private + protected + default |
getMethods() | Class + all superclasses | public only |
getDeclaredMethods() | This class only | All access levels |
getConstructors() | This class only | public only |
getDeclaredConstructors() | This class only | All access levels |
Memory Diagram
1Eagle.class2 ├── public field: breed ← returned by BOTH getFields() and getDeclaredFields()3 ├── private field: canSwim ← returned by getDeclaredFields() ONLY4 └── (inherited from Object)5 └── no public fields ← getFields() searches here too, finds nothing6
7getMethods() → [fly (Eagle), wait (Object), notify (Object), equals (Object), ...]8getDeclaredMethods() → [fly (Eagle), eat (Eagle)] ← private eat included, no Object methods12. Why Reflection Should Be Avoided
There are two strong reasons to avoid reflection in normal application code:
Reason 1 It Breaks Encapsulation
Object-oriented programming is built on the principle of encapsulation: private members are private for a reason. They represent internal implementation details that other classes should not access or modify.
Reflection completely bypasses this:
1// Developer's intention:2private String secretApiKey = "sk-abc123";3
4// Reflection destroys that intention:5Field f = obj.getClass().getDeclaredField("secretApiKey");6f.setAccessible(true);7String stolen = (String) f.get(obj); // reads private data8f.set(obj, "tampered-key"); // overwrites private dataThere is no way to prevent this in standard Java (short of a SecurityManager, which is deprecated in Java 17+).
Reason 2 It is Slow
Reflection works at runtime by doing name-based lookups. Every time you call getMethod("fly"), the JVM must:
- Search through the class's method list by string comparison.
- Resolve parameter types.
- Perform access checks (or bypass them).
- Call the method dynamically.
Compare this to a direct method call, which is resolved at compile time, inlined by the JIT compiler, and executed as a single machine instruction.
Reflection overhead is typically 10–100x slower than direct access for individual operations.
1// Direct call — compiled, JIT-optimized, fast:2eagle.fly();3
4// Reflection — runtime lookup, no JIT optimization, slow:5Method m = Eagle.class.getDeclaredMethod("fly");6m.invoke(eagle);Reason 3 It Defeats IDE and Compiler Safety
When you use reflection with string-based names:
- The IDE cannot check if
"fly"actually exists. - The compiler cannot catch typos.
- Errors only surface at runtime as
NoSuchMethodException.
1// Typo — compiler is silent, IDE is silent, crashes at runtime:2Method m = Eagle.class.getDeclaredMethod("fyl"); // NoSuchMethodException at runtimeSummary of Disadvantages
| Disadvantage | Impact |
|---|---|
| Breaks encapsulation | Private members can be accessed/modified by anyone |
| Runtime performance | 10–100x slower than direct access |
| No compile-time safety | Typos in method/field names only fail at runtime |
| Breaks Singleton | Private constructors can be invoked |
| Complexity | Code is harder to read, debug, and maintain |
13. When Reflection IS Used
Despite its dangers, reflection is used in specific scenarios where there is no alternative:
| Use Case | Example |
|---|---|
| Frameworks and libraries | Spring, Hibernate, JUnit all use reflection to instantiate classes, inject dependencies, and call test methods at runtime |
| Serialization | Java serialization reads and writes private fields via reflection |
| Dependency Injection | Spring's @Autowired uses reflection to find and set fields |
| ORM frameworks | Hibernate maps database columns to Java fields, including private ones |
| Plugin systems | Loading and calling classes by name from config files at runtime |
| Testing frameworks | JUnit uses reflection to discover and invoke test methods |
| IDE tools | Code completion, refactoring, debuggers inspect class structure |
| Annotation processing | Frameworks read annotations on classes and methods at runtime |
14. Mermaid Diagrams
JVM Class Loading and Class Object Creation
Three Ways to Get a Class Object
Reflection Capability Map
How Reflection Breaks Singleton
15. Quick-Reference Tables
All Reflection Methods at a Glance
| Target | Public + Inherited | All in This Class Only |
|---|---|---|
| Methods | getMethods() | getDeclaredMethods() |
| Fields | getFields() | getDeclaredFields() |
| Constructors | getConstructors() | getDeclaredConstructors() |
| Single method | getMethod(name, paramTypes...) | getDeclaredMethod(name, paramTypes...) |
| Single field | getField(name) | getDeclaredField(name) |
| Single constructor | getConstructor(paramTypes...) | getDeclaredConstructor(paramTypes...) |
`java.lang.reflect` Key Classes
| Class | Purpose |
|---|---|
Class | Entry point — represents a class/interface at runtime |
Method | Represents a method; can be invoked |
Field | Represents a field; can be read/written |
Constructor | Represents a constructor; can be invoked |
Modifier | Utility to decode modifier integers to readable strings |
Parameter | Represents a method/constructor parameter |
Annotation | Base for all annotations — readable via reflection |
Private Access Bypass
| Step | Code |
|---|---|
| Get the private member | getDeclaredMethod() / getDeclaredField() / getDeclaredConstructor() |
| Bypass access check | .setAccessible(true) |
| Use it | .invoke() / .get() / .set() / .newInstance() |
16. Common Mistakes
Mistake 1: Using `getMethod()` to Find a Private Method
1Method m = eagleClass.getMethod("eat"); // ❌ NoSuchMethodException2// getMethod only returns public methodsFix: Use getDeclaredMethod():
1Method m = eagleClass.getDeclaredMethod("eat"); // ✅2m.setAccessible(true);Mistake 2: Forgetting `setAccessible(true)` for Private Members
1Field canSwim = eagleClass.getDeclaredField("canSwim");2canSwim.set(instance, true); // ❌ IllegalAccessExceptionFix:
1canSwim.setAccessible(true); // ✅2canSwim.set(instance, true);Mistake 3: Wrong Parameter Types in `getMethod()`
1// Eagle.fly(int, boolean, String) — correct signature2Method m = eagleClass.getMethod("fly", Integer.class, Boolean.class, String.class);3// ❌ NoSuchMethodException — must use primitive types, not wrappersFix: Use primitive class literals for primitive parameters:
1Method m = eagleClass.getMethod("fly", int.class, boolean.class, String.class); // ✅Mistake 4: Passing Wrong Argument Types to `invoke()`
1// Method signature: fly(int, boolean, String)2method.invoke(instance, "120", "true", "North"); // ❌ IllegalArgumentException3// Strings passed for int and booleanFix: Match argument types exactly:
1method.invoke(instance, 120, true, "North"); // ✅Mistake 5: Not Handling Checked Exceptions
1Class<?> cls = Class.forName("Eagle"); // ❌ unhandled ClassNotFoundExceptionFix:
1try {2 Class<?> cls = Class.forName("Eagle");3} catch (ClassNotFoundException e) {4 e.printStackTrace();5}6// or declare: throws ClassNotFoundExceptionMistake 6: Using `newInstance()` (Deprecated)
1Eagle e = (Eagle) eagleClass.newInstance(); // ❌ deprecated in Java 9+Fix: Use getDeclaredConstructor().newInstance():
1Eagle e = eagleClass.getDeclaredConstructor().newInstance(); // ✅17. Best Practices
- Avoid reflection in application code. Use it only in framework/library code where it is truly necessary.
- Prefer compile-time type safety wherever possible. Reflection sacrifices this, making code harder to maintain and debug.
- Always handle exceptions thrown by reflection methods (
ClassNotFoundException,NoSuchMethodException,IllegalAccessException,InvocationTargetException).
- Never use
setAccessible(true)on production business logic — it is a code smell indicating poor design. Consider if the design can be changed to make the member accessible through a proper API.
- Cache reflection results if you must use them repeatedly. Calling
getMethod()in a loop is extremely slow. Store theMethod/Fieldobject and reuse it:
1 // ❌ Slow — method lookup on every call2 for (Data d : dataList) {3 eagleClass.getMethod("fly").invoke(eagle);4 }5
6 // ✅ Cache the Method object7 Method flyMethod = eagleClass.getMethod("fly");8 for (Data d : dataList) {9 flyMethod.invoke(eagle);10 }- Protect Singleton from reflection by throwing an exception in the constructor if an instance already exists, or use
enum-based Singleton.
- Document clearly when and why reflection is used — it is never obvious to the reader.
18. Interview Notes
Most Frequently Asked Questions
Q1: What is Java Reflection?
A: Java Reflection is an API (java.lang.reflect) that allows a program to inspect and manipulate the structure of classes, methods, fields, and constructors at runtime — even private ones. It is typically used by frameworks like Spring, Hibernate, and JUnit.
Q2: What is the Class class in Java?
A: java.lang.Class is a class whose instances represent classes and interfaces at runtime. The JVM automatically creates one Class object for every class it loads, containing that class's metadata (methods, fields, constructors, modifiers, superclass, etc.).
Q3: What are the three ways to get a Class object?
A:
Class.forName("ClassName")— string-based, most dynamic, throwsClassNotFoundExceptionClassName.class— compile-time literal, safest and fastestobject.getClass()— when you already have an instance
Q4: What is the difference between getMethods() and getDeclaredMethods()?
A: getMethods() returns all public methods of the class and its inherited superclasses. getDeclaredMethods() returns all methods (public AND private) declared directly in that class, with no inherited methods.
Q5: How can you access a private field using reflection?
A:
getDeclaredField("fieldName")— gets the private fieldfield.setAccessible(true)— bypasses access restrictionfield.get(instance)/field.set(instance, value)— read or write
Q6: Can reflection break the Singleton pattern?
A: Yes. By using getDeclaredConstructor() and setAccessible(true), you can call a private constructor and create additional instances, breaking the Singleton guarantee. Protection: throw an exception inside the constructor if an instance already exists, or use an enum-based Singleton.
Q7: Why is reflection slow?
A: Reflection operates at runtime, performing string-based name lookups for methods and fields. These lookups cannot be compiled or JIT-optimized the way direct calls are. The overhead is typically 10–100x compared to direct method invocation.
Q8: What is setAccessible(true) and why is it dangerous?
A: It instructs the JVM to suppress its access control checks for a specific Method, Field, or Constructor. This allows you to access private members from any class. It is dangerous because it breaks encapsulation — the fundamental OOP principle that private members are internal implementation details.
Q9: When is reflection legitimately used?
A: In frameworks and tools: Spring (dependency injection), Hibernate (ORM), JUnit (test discovery), Java serialization, IDE tools, annotation processors, and plugin/extension systems. Application-level code generally should not use it.
Q10: What is InvocationTargetException in reflection?
A: When a method invoked via method.invoke() throws an exception, that exception is wrapped in InvocationTargetException. You need to call e.getCause() to get the original exception.
19. Practice Questions
Easy
- What package contains the reflection API classes (
Method,Field,Constructor)? - Name the three ways to get a
Classobject in Java. - What is the difference between
getFields()andgetDeclaredFields()? - Which method do you call to bypass private access in reflection?
- Does
getMethods()return private methods? Does it return inherited methods?
Medium
- Write a program that uses reflection to print the name, return type, and modifier of every method declared in a class
Person(including private methods).
- Write a program that uses reflection to read and then change the value of a
privatefield namedsalaryin anEmployeeclass.
- Write a program that uses
Class.forName("java.util.ArrayList")and prints all public methods ofArrayList.
- Demonstrate how reflection breaks the Singleton pattern. Then modify the Singleton class to protect against it.
- Why does
getMethod("fly", Integer.class)fail when the actual method signature isfly(int)? What is the fix?
Hard
- Write a program that uses reflection to invoke a private method
calculateTax(double amount)on anInvoiceclass without modifying that class.
- Create a generic method
printClassInfo(Object obj)that uses reflection to print the class name, all field names and values, and all method names of the passed object.
- Explain the full execution flow when
method.invoke(obj, args)is called — from the Java code down to JVM method dispatch.
- Implement a simple dependency injection framework (like Spring's
@Autowired) using reflection — scan a class for fields annotated with a custom@Injectannotation and set their values automatically.
- Why is an
enum-based Singleton immune to reflection attacks? Show the Java specification behavior that prevents it.
20. Summary Cheat Sheet
1┌─────────────────────────────────────────────────────────────────────────────┐2│ JAVA REFLECTION — QUICK SUMMARY │3├─────────────────────────────────────────────────────────────────────────────┤4│ DEFINITION │5│ API to inspect and modify classes/methods/fields/constructors at runtime. │6│ Package: java.lang.reflect Entry point: java.lang.Class │7├─────────────────────────────────────────────────────────────────────────────┤8│ GET THE CLASS OBJECT (3 ways) │9│ Class.forName("Eagle") → dynamic, throws ClassNotFoundException │10│ Eagle.class → compile-time safe, no exception │11│ obj.getClass() → when you have an instance │12├─────────────────────────────────────────────────────────────────────────────┤13│ WHAT YOU CAN DO WITH IT │14│ getMethods() → public methods + inherited (from Object too) │15│ getDeclaredMethods() → all methods (public+private), this class only │16│ getFields() → public fields + inherited │17│ getDeclaredFields() → all fields (public+private), this class only │18│ getDeclaredConstructors() → all constructors including private │19├─────────────────────────────────────────────────────────────────────────────┤20│ ACCESSING PRIVATE MEMBERS │21│ 1. getDeclaredMethod/Field/Constructor (name, types...) │22│ 2. .setAccessible(true) ← bypasses private access check │23│ 3. .invoke() / .get() / .set() / .newInstance() │24├─────────────────────────────────────────────────────────────────────────────┤25│ REFLECTION BREAKS SINGLETON │26│ getDeclaredConstructor() → setAccessible(true) → newInstance() │27│ Fix: throw exception if instance != null inside constructor │28│ Best fix: use enum-based Singleton (immune to reflection) │29├─────────────────────────────────────────────────────────────────────────────┤30│ WHY TO AVOID REFLECTION │31│ ❌ Breaks encapsulation (private is no longer private) │32│ ❌ Slow (runtime name lookup, no JIT optimization) │33│ ❌ No compile-time safety (typos only caught at runtime) │34│ ❌ Increases code complexity │35├─────────────────────────────────────────────────────────────────────────────┤36│ WHEN IT IS USED │37│ ✅ Frameworks: Spring, Hibernate, JUnit, Jackson │38│ ✅ Serialization, annotation processing, plugin systems │39│ ✅ IDE tools and debuggers │40│ ❌ NOT in normal application code │41└─────────────────────────────────────────────────────────────────────────────┘End of Chapter — Java Reflection
Next Topics: Exception Handling · Singleton Pattern (in depth) · Design Patterns · Java 8 Features
Mastery check
How well can you recall this?
Finished this lesson?