ProgrammingBackend Developer

What is reflection in Java? What are its advantages, disadvantages, and potential risks when used?

Pass interviews with Hintsage AI assistant

Answer

Reflection is a mechanism that allows you to inspect and modify the structure and behavior of classes, objects, methods, and fields at runtime. It is implemented through the java.lang.reflect package.

It allows:

  • To obtain information about classes at runtime
  • To invoke methods and access fields dynamically
  • To create new class instances by name

Example:

import java.lang.reflect.Method; public class ReflectionExample { public void greet() { System.out.println("Hello!"); } public static void main(String[] args) throws Exception { Class<?> clazz = Class.forName("ReflectionExample"); Object instance = clazz.getDeclaredConstructor().newInstance(); Method method = clazz.getMethod("greet"); method.invoke(instance); // Outputs: Hello! } }

Advantages:

  • Flexibility and extensibility (e.g., frameworks, DI)
  • Ability to use generic code for operations with objects without knowing their types in advance

Disadvantages/Risks:

  • Performance degradation
  • Potential security issues (bypassing access modifiers)
  • Breaks encapsulation
  • Reduced maintainability

Tricky Question

Can private fields and methods of a class be accessed using reflection, and what are the consequences of this?

Answer: Yes, it is possible using the setAccessible(true) method on Field or Method:

Field field = clazz.getDeclaredField("privateField"); field.setAccessible(true); field.set(obj, "value");

This violates class encapsulation and carries risks: the situation becomes fragile, there may be security errors, and in new versions of the JVM such actions can be restricted by access policies.

Examples of Real Errors Due to Lack of Understanding of the Topic


Story

In a large project for automatic DTO mapping through reflection, fields of type "Optional" were not handled correctly, leading to NullPointerException during bulk data processing, as the reflection package could not differentiate between Optional values and null.


Story

In banking software, access to private fields was implemented via setAccessible(true) for serialization. After a JVM update, the behavior changed, access to the private field was restricted, and important serialization functionality suddenly stopped working in production.


Story

In an ORM framework, the cache of reflection was forgotten to be refreshed after the data schema was changed. As a result, the system threw unpredictable exceptions when dealing with new class fields that were not reflected in the cache.