DEV Community

Cover image for Java Reflection
MR.H
MR.H

Posted on

Java Reflection

Reflection is an API in java to modify the behaviour of the code in runtime. It allows options to invoke a class, methods, fields dynamically.

How it works?

Java Reflection works by examining the bytecode of a class at runtime, and providing a way to interact with its members programmatically. Reflection can be used to create new instances of classes, inspect the properties of objects, and invoke methods dynamically.

Uses of Reflection

  • Dynamic loading of classes : Reflection can be used to dynamically load classes at runtime. This can be useful when the name of the class is not known until runtime, or when you need to load classes from external sources such as JAR files.
  • Examine the properties of objects: Reflection can be used to examine the properties of objects at runtime. This can be useful for debugging or logging purposes.
  • Dynamically invoke methods: Reflection can be used to dynamically invoke methods on objects at runtime. This can be useful when the exact method to be invoked is not known until runtime, or when you need to invoke methods based on user input.
  • Creating new instances of classes: Reflection can be used to create new instances of classes at runtime. This can be useful when you need to create objects dynamically based on user input or other runtime conditions.

Limitations

  • Reflection is relatively slow and can have performance implications.
  • Reflection can make your code more complex and difficult to maintain
  • Reflection will make your code less secure as it has access to private methods and fields which should not be accessed directly

Example

import java.lang.reflect.Field;
import java.lang.reflect.Method;

class Test {
    public static void main(String[] args) throws Exception {
        //Creating a object for the class person
        Person employee = new Person("employee 1", "employee1@example.com");

        // Creating class object from the object using getClass() method
        Class employeeClass = employee.getClass();

        // Printing the class name using getName()
        System.out.println("The name of the class is " + employeeClass.getName());


        // Getting field by passing the field name
        Field emailField = employeeClass.getDeclaredField("email");
        emailField.setAccessible(true);
        System.out.println("The email of the employee is " + emailField.get(employee));


        Field nameField = employeeClass.getDeclaredField("name");

        //Since name is a private field. we are changing its access modifier
        nameField.setAccessible(true);
        // Updating name field value
        nameField.set(employee, "Employee 2");
        nameField.setAccessible(false);

        Method getNameWithPrefix = employeeClass.getMethod("getName", String.class);

        String updatedName = (String) getNameWithPrefix.invoke(employee, "Mr.");

        System.out.println("The name of the employee is " + updatedName);
    }
}

class Person {
    private String name;
    private String email;

    public Person(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return this.name;
    }

    public String getName(String prefix) {
        return prefix + " " + this.name;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

The name of the class is Person
The email of the employee is employee1@example.com
The name of the employee is Mr. Employee 2
Enter fullscreen mode Exit fullscreen mode

Conclusion

Java reflection can be used to modify the behaviour of a java code in runtime and dynamically loading of classes in runtime. However, Reflection should be used carefully as it will have performance issues and security implications.


Leave a like and share your thoughts in the comment section

HAPPY CODING

Cover Photo by Zoltan Tasi on Unsplash

Top comments (0)