Reflection in Java
The Java Reflection is a mechanism that allows to inspect and interact with components of the Java class at runtime. It provides a way to examine or modify the runtime behavior of the applications.
- Class Object: The Class clazz in Java is the entry point for the Reflection. It provides methods to inspect the properties of class.
- Field Reflection: Accessing and modifying the fields of the class dynamically.
- Method Reflection: Invoking methods inspecting method signatures and handling method invocation at the runtime.
- Constructor Reflection: To Create new instances of the class using its constructors dynamically.
Use Cases:
- Dynamic Loading: The Loading classes dynamically at runtime.
- Introspection: Examining and manipulating classes and fields.
- Serialization and Deserialization: The Achieving custom serialization processes.
Example of Java Reflection:
Java
//Java program to demonstrate Java Reflection import java.io.*; import java.lang.reflect.*; public class GFG { public static void main(String[] args) { Class<?> clazz = someClass. class ; // Get all methods Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { System.out.println( "Method Name: " + method.getName()); } } } class someClass { public void method1() { /* ... */ } public void method2() { /* ... */ } } |
Method Name: method1 Method Name: method2
Deep Dive into Java Reflection and Annotations
The Java Reflection and Annotations are powerful features that provide dynamic and metadata-driven capabilities to Java applications. The Reflection allows the examination and manipulation of the class properties, methods, and fields at runtime while Annotations provide a way to add metadata and behavior to the code.