What happens if a final field is changed using reflection?

A final field is intended to be assigned only once, providing immutability and consistency. Although Java's Reflection API can be used to modify a final field by bypassing access checks, doing so violates the design contract of the class and can lead to unexpected behavior because the JVM may optimize code under the assumption that final fields never change.

Key Points: • Reflection can bypass normal access restrictions and modify a final field at runtime. • Changing a final field breaks immutability and may produce inconsistent results due to JVM optimizations. • Such modifications should be avoided because they can make applications difficult to debug and maintain.

Example: Consider a configuration object containing a final application ID. If reflection changes this value after initialization, some parts of the application may use the updated value while others may still rely on the original value cached by the JVM, leading to unpredictable behavior.

Code Example:

import java.lang.reflect.Field;

class Employee {

    private final String name = "John";

    public String getName() {
        return name;
    }
}

public class ReflectionExample {

    public static void main(String[] args) throws Exception {

        Employee emp = new Employee();

        Field field = Employee.class.getDeclaredField("name");
        field.setAccessible(true);

        field.set(emp, "David");

        System.out.println(emp.getName());
    }
}

Interview Tip: A concise interview answer is: Reflection can modify a final field by bypassing access checks, but doing so breaks the immutability guarantee. Since the JVM may optimize based on the assumption that final fields never change, modifying them through reflection can result in inconsistent and unpredictable behavior.