Middle
What is reflection in Java and what is it used for?
sobes.tech AI
Answer from AI
Reflection in Java is a mechanism that allows a program to obtain information about classes, methods, fields, and constructors at runtime, as well as to dynamically invoke methods and create objects.
It is used for:
- Inspecting classes and objects without knowing their structure at compile time.
- Creating universal libraries and frameworks (e.g., for serialization, ORM, testing).
- Dynamically invoking methods and changing the behavior of the program.
Example of using reflection:
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); // result will be "world"
Here, we dynamically invoke the substring method on a string without directly calling it in the code.