Junior — Middle
Can you show an example of when and how Reflection API is used in Java?
sobes.tech AI
Answer from AI
The Reflection API in Java allows exploring and modifying the behavior of programs at runtime. It is useful when you need to dynamically create objects, invoke methods, or obtain information about classes without knowing their structure at compile time.
Example of usage: suppose you have a class, the name of which comes as a string, and you want to create an instance of it and call a method without directly referencing the class.
public class ReflectionExample {
public static void main(String[] args) throws Exception {
String className = "java.util.ArrayList";
Class<?> clazz = Class.forName(className); // load class by name
Object instance = clazz.getDeclaredConstructor().newInstance(); // create object
// call the add method
Method addMethod = clazz.getMethod("add", Object.class);
addMethod.invoke(instance, "Example");
System.out.println(instance); // output: [Example]
}
}
Reflection is often used in frameworks, for example, for dependency injection, serialization, testing, etc.