Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution.
- A class object is associated for every loaded class by the JVM.
- The class object reflects the class it represents The primitive Java types are also represented as class objects.
- Instances of class class stores information about classes: Class name, Inheritance , Interfaces implemented ,Methods and fields.
- Enables method invocation and field referencing by name.
Sample Example:
import java.lang.reflect.Method;
import java.util.Date;
public class ReflectionExample {
public static void main(String[] args) {
Date date = new Date();
Class objCass = String.class;
Method[] methods = objCass.getMethods();
for (Method method : methods) {
System.out.println("************************");
System.out.println("Method Name : " + method.getName());
System.out.println("Method Parameters types : "
+ method.getParameterTypes());
System.out.println("Method return types : "
+ method.getReturnType());
}
}
}