KEMBAR78
Reflection Document | PDF
0% found this document useful (0 votes)
11 views2 pages

Reflection Document

Java reflection

Uploaded by

ehsryturysuj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Reflection Document

Java reflection

Uploaded by

ehsryturysuj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Java Reflection: Inspecting and Modifying Code at Runtime

Java Reflection is a powerful feature in the Java programming language that allows a program to
examine and manipulate its own structure and behavior at runtime. It is part of the
java.lang.reflect package and is commonly used for dynamic class loading, debugging,
testing, or building frameworks like Spring and Hibernate.

Key Capabilities of Java Reflection:


1. Inspect Classes and Interfaces
You can get information about class names, modifiers, fields, methods, and constructors even if
you don’t know them at compile time.
2. Access Private Members
Reflection allows access to private fields and methods using setAccessible(true),
which bypasses normal access controls.
3. Create Objects Dynamically
You can instantiate classes at runtime using Class.forName() and newInstance().

4. Invoke Methods Dynamically


Methods can be called on objects without knowing the method name beforehand using
Method.invoke().

Example:
import java.lang.reflect.*;

public class ReflectionExample {

public static void main(String[] args) throws Exception {

Class<?> clazz = Class.forName("java.util.ArrayList");

Method[] methods = clazz.getDeclaredMethods();

for (Method method : methods) {

System.out.println(method.getName());

This code lists all the methods of the ArrayList class.

Use Cases:
• Frameworks: Dependency injection, ORM tools, and serializers use reflection to operate on
unknown classes.
• Testing: Unit tests use reflection to test private methods.
• Development Tools: IDEs and debuggers rely on it to provide code analysis.

Drawbacks:
• Performance Overhead: Reflection is slower than direct code execution.
• Security Concerns: It can break encapsulation and access sensitive data.
• Complexity: It can make code harder to understand and maintain.
Java Reflection is a double-edged sword—powerful, but to be used carefully and only when necessary.
Would you like a practical example with a custom class?

You might also like