DEV Community

Cover image for Java - Reflection
Yiğit Erkal
Yiğit Erkal

Posted on

Java - Reflection

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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());
)
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)