Reflection and Dynamic Class Loading are advanced features in Java that allow a program
to inspect and manipulate itself at runtime. They are distinct but often used together to
achieve highly flexible and extensible applications.
1. Reflection
Java Reflection is the ability of a program to examine or modify the runtime behavior of
classes, interfaces, fields, and methods. It provides a way to interact with the structure of your
code during execution, even if you don't have prior knowledge of the classes at compile time.
Key Concepts
● [Link]: This is the entry point for all reflection operations. Every object in Java
has a method getClass(), which returns a Class object that represents the class of that
object. You can also get a Class object using [Link]("[Link]")
or [Link].
● [Link] Package: This package contains classes that represent the structural
elements of a class:
○ Constructor: Represents a single constructor. Used to create new instances
dynamically.
○ Method: Represents a single method. Used to invoke methods dynamically.
○ Field: Represents a single field (class variable or instance variable). Used to get and
set field values dynamically.
What Reflection Allows You to Do
1. Introspection: Discover the names of all members (fields, methods, constructors) of a
class.
2. Instantiation: Create new instances of classes dynamically using a Constructor object or
[Link]() (now generally discouraged in favor of [Link]()).
3. Method Invocation: Call methods dynamically using a Method object.
4. Access/Modification: Get and set the values of fields (even private ones) using a Field
object and setting its accessible flag to true.
Use Cases for Reflection
● Frameworks (e.g., Spring, JUnit): Used for dependency injection, object-relational
mapping, and annotation processing.
● Serialization/Deserialization (e.g., JSON/XML parsers): Used to inspect object fields
and map them to external data formats.
● Debugging and Testing: Used by tools to inspect the state of objects, including private
members.
2. Dynamic Class Loading
Dynamic Class Loading is the process of loading a Java class into the Java Virtual Machine
(JVM) at runtime, rather than at compile time or application startup. This mechanism is
fundamental to the flexibility of the Java platform.
Key Concepts
● [Link]: This abstract class is responsible for loading Java classes. Every
class is loaded by an instance of a ClassLoader subclass.
○ When the JVM needs a class, it asks the appropriate class loader to find and load the
corresponding .class file (or binary representation) and define a Class object for it.
● Class Loader Hierarchy (Delegation Model): Class loaders are organized hierarchically.
When a class loader is asked to load a class, it typically delegates the request up to its
parent before attempting to load it itself. The common built-in hierarchy is:
1. Bootstrap ClassLoader: Loads core Java classes (like [Link]) from the
standard Java runtime libraries. It has no parent and is implemented natively.
2. Platform ClassLoader: Loads platform classes.
3. System ClassLoader (Application ClassLoader): Loads classes from the
application's classpath.
● Key Methods for Dynamic Loading:
○ [Link](String className): Loads and links the class with the specified
name. If the class isn't already loaded, the appropriate class loader is called.
○ [Link](String name): Directly invokes the class loader mechanism
to load the class.
Why Use Dynamic Class Loading?
● Lazy Loading: Classes are loaded only when they are needed, which conserves memory
and speeds up application startup.
● Plugins and Extensibility: Allows an application to load new modules (plugins) from
external JAR files or network locations without restarting the main application.
● Code Isolation: Custom class loaders can create separate namespaces, which is
essential for environments like application servers (e.g., Tomcat) where multiple distinct
web applications run simultaneously without interfering with each other's classes.
3. Example: Combining Dynamic Class Loading and
Reflection
This example demonstrates how to dynamically load a class from a name known only at
runtime (using [Link]()) and then use Reflection to create an instance and invoke a
method.
The Class to be Loaded Dynamically ([Link])
Imagine this class is in a separate module or location, and our main program doesn't know
about it at compile time.
Java
// [Link]
package [Link];
public class DynamicWorker {
public void executeTask() {
[Link]("DynamicWorker: Executing a task known only at runtime!");
}
}
The Main Application ([Link])
The main application will load the class and invoke its method using reflection.
Java
// [Link]
import [Link];
import [Link];
public class ReflectiveApp {
public static void main(String[] args) {
String className = "[Link]";
String methodName = "executeTask";
try {
// 1. Dynamic Class Loading
// Get the Class object for the class name (fully qualified)
Class<?> workerClass = [Link](className);
[Link]("Class loaded successfully: " + [Link]());
// 2. Reflection - Instantiation
// Get the no-argument constructor
Constructor<?> constructor = [Link]();
// Create a new instance of the class
Object workerInstance = [Link]();
[Link]("Instance created: " + workerInstance);
// 3. Reflection - Method Invocation
// Get the Method object for the specified method name and parameter types (none)
Method taskMethod = [Link](methodName);
[Link]("Method found: " + [Link]());
// Invoke the method on the created instance
[Link](workerInstance);
} catch (ClassNotFoundException e) {
[Link]("Error: Class not found. " + [Link]());
} catch (Exception e) {
[Link]();
}
}
}
/*
Expected Output:
Class loaded successfully: [Link]
Instance created: [Link]@...
Method found: executeTask
DynamicWorker: Executing a task known only at runtime!
*/