Sobes.tech
Junior — Middle

Explain what Reflection API in Java is and how it is used for dynamic work with classes and their objects.

sobes.tech AI

Answer from AI

The Reflection API in Java allows a program to obtain information about classes, methods, fields, and constructors at runtime, as well as to create objects and invoke methods dynamically without knowing them at compile time. This is useful for creating flexible and extensible applications, such as in frameworks, testing tools, or when working with annotations.

Example of using Reflection to invoke a method:

Class<?> clazz = Class.forName("java.lang.String");
Method method = clazz.getMethod("substring", int.class, int.class);
String str = "Hello, world!";
String result = (String) method.invoke(str, 7, 12); // "world"

Here, we dynamically obtained the String class, the substring method, and invoked it on the str object without using a direct call in the code.