Junior — Middle
Explain the principle of reflection mechanism in Java and its main applications.
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 modify field values.
Main uses of reflection:
- Frameworks and libraries (e.g., Spring) use reflection for dependency injection, object creation, and method invocation without explicit knowledge of classes at compile time.
- Serialization and deserialization of objects.
- Testing (e.g., JUnit) for invoking test methods.
- Tools for code analysis and debugging.
Example of using reflection to invoke a method:
Class<?> clazz = Class.forName("com.example.MyClass");
Object obj = clazz.getDeclaredConstructor().newInstance();
Method method = clazz.getMethod("myMethod", String.class);
method.invoke(obj, "hello");
Reflection is powerful, but its use can impact performance and security, so it should be used consciously.