Sobes.tech
Junior — Middle

What is the main purpose of Reflection API in working with objects and classes?

sobes.tech AI

Answer from AI

The Reflection API in Java allows programmatically exploring and modifying the structure of classes, objects, methods, and fields at runtime.

The main purpose is to enable dynamic retrieval of information about classes (such as their methods, fields, constructors), creating objects, invoking methods, and changing fields without prior knowledge at compile time.

This is useful for frameworks, libraries, serialization tools, testing, and other cases where working with classes that are not known in advance is necessary.

Example of using Reflection to invoke a method:

import java.lang.reflect.Method;

public class ReflectionExample {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("java.lang.String");
        Method method = clazz.getMethod("toUpperCase");
        String str = "hello";
        String result = (String) method.invoke(str);
        System.out.println(result); // HELLO
    }
}
What is the main purpose of Reflection API in working… - sobes.tech