Reflection in Java
Let's say You are working on automation and your client or team lead want you to write the name of the test cases which is getting executed .
Now tell me how will you do that ???
We can achieve this easily using reflection
Basically, Java Reflection is a process of examining or modifying the run time behavior of a class at run time.
The [Link] class provides many methods that can be used to get metadata, examine and change the run time behavior of a class.
The [Link] and [Link] packages provide classes for java reflection.
Java reflection can be used to get many information at runtime, but we will be looking at getting/fetching below info at runtime:
1. Get Object class name.
2. Get declared constructors of a class.
3. Get declared methods of a class.
1. Get class name of an Object:-
public class ReflectionTest {
public int var1;
private int var2;
public ReflectionTest()
{
}
private ReflectionTest(int i)
{
}
public void m1()
{
}
private void m2()
{
}
}
public class Demo {
public static void main(String[] args) {
ReflectionTest obj = new ReflectionTest();
Class clazz= [Link]();
[Link]("Name of the class of the object-->"+[Link]());
for(Constructor c:[Link]())
{
[Link]([Link]());
}
[Link]([Link]().length);
for(Constructor c:[Link]())
{
[Link]([Link]());
}
}
2. Get list of methods:-
public class Main {
public static void main(String[] args) {
Class aClass = [Link];
// Get the methods
Method[] methods = [Link]();
// Loop through the methods and print out their names
for (Method method : methods) {
[Link]([Link]());
}
}
}
3. Get method return types:-
public class A {
public static void main(String[] args) {
A a= new A();
Class clazz=[Link]();
[Link]([Link]());
for(Method m:[Link]())
{
[Link]([Link]());
[Link]([Link]().getName());
//[Link]([Link]);
}
}
public void m1()
{
}
}
Similarly we can find/access the declared constructors as well.