Java - Reflection
Yiğit Erkal
Posted on April 27, 2022
Reflection feature helps us to access classes, methods, variables and other properties of objects. Moreover, it is used to get, control and manage information such as class, method, properties and annotation such as name, parameter. We do this already by defining a variable and when we put "." with the completion of the IDE.
Student student = new Student()
student.
// IDE offers us features such as methods or variables here
To start with, a simple Student class
public class Student {
public final static int id = 4;
private String name;
private int age;
public Metallica () {
this ("James", 54);
}
//... other getters and setter
}
and here is our test class to test what is reflection
Class<?> myClass = Class.forName("com.org.Student");
Object obj = myClass.newInstance();
// varargs can be used for getDeclaredConstructor
Constructor<?> cons = myClass.getDeclaredConstructor(String.class, Integer.TYPE);
for (Field field: myClass.getDeclaredFields())
(
System.out.println("Field:" + field.getName());
)
Field:id
Field:name
Field:age
Although there is no access to a private field other than getter and setter, we obtained the names of those variables 💡 So this is more beneficial in test and debug.
In the same way we can get the modifiers...
int modifier = cons.getModifiers();
System.out.println("Modifer: " + Modifier.toString(modifier));
Modifier: public
Because our Student class implemented as public.
Moreover, we can invoke public, private and static methods via invoke() in order to get the required information from them.
Posted on April 27, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.