Java Reflection
Java Reflection is a feature that allows a Java program to examine or introspect the classes, interfaces, fields, methods, and constructors of an object at runtime. With reflection, it's possible to examine an object's properties and methods and access them dynamically, without having to know their names at compile-time. Reflection is commonly used in Java frameworks such as Spring and Hibernate, which rely on it to dynamically create objects, invoke methods, and access fields.
The java.lang.reflect
package provides the classes and interfaces for using reflection in Java.
Here are some examples of what you can do with reflection:
- Get the class of an object:
Class<?> clazz = object.getClass();
- Get the constructors of a class:
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
- Get the fields of a class:
Field[] fields = clazz.getDeclaredFields();
- Get the methods of a class:
Method[] methods = clazz.getDeclaredMethods();
- Create a new instance of a class:
Object newInstance = clazz.newInstance();
- Invoke a method on an object:
Object result = method.invoke(object, args);
- Access a field of an object:
Object value = field.get(object);
Note that reflection can be slower and less efficient than direct method and field access, since it involves additional runtime overhead. Additionally, because reflection bypasses some of the normal checks that occur at compile-time, it can be less type-safe and more error-prone. Therefore, it's generally recommended to use reflection only when necessary, and to favor direct method and field access whenever possible.