In this tutorial, we will learn reflection, a feature in Java programming that allows us to inspect and modify classes, methods, etc.
Java Reflection is a process of examining or modifying the run time behavior of a class at run time.
The java.lang.Class class provides many methods that can be used to get metadata, examine and change the run time behavior of a class.
The required classes for reflection are provided under java.lang.reflect package.
Reflection gives us information about the class to which an object belongs and also the methods of that class which can be executed by using the object.
Through reflection we can invoke methods at runtime irrespective of the access specifier used with them.
Example: Constructor reflection:
import java.lang.Class;
import java.lang.reflect.*;
class Dog {
public Dog() {
}
public Dog(int age) {
}
private Dog(String sound, String type) {
}
}
class ReflectionDemo {
public static void main(String[] args) {
try {
Dog d1 = new Dog();
Class obj = d1.getClass();
// get all the constructors in a class using getDeclaredConstructor()
Constructor[] constructors = obj.getDeclaredConstructors();
for(Constructor c : constructors) {
// get names of constructors
System.out.println("Constructor Name: " + c.getName());
// get access modifier of constructors
int modifier = c.getModifiers();
System.out.println("Modifier: " + Modifier.toString(modifier));
// get the number of parameters in constructors
System.out.println("Parameters: " + c.getParameterCount());
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Output
Constructor Name: Dog
Modifier: public
Parameters: 0
Constructor Name: Dog
Modifier: public
Parameters: 1
Constructor Name: Dog
Modifier: private
Parameters: 2