Hacking into java immutable class, and protecting them from modification through reflection

Reading Time: < 1 minute

In my previous article I had explained how to make a class immutable. Taking that as an example, it shows how do you write a perfectly immutable class. However, there is a catch. And that is reflection. Since one can access and modify private fields through reflection, it can break the sanctity of the immutable object.

If you execute this code:

Immutable obj = new Immutable(1, "yadav", address, addressList); 
Field nameField = obj.getClass().getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(obj, "ankit");

it breaks the whole concept of immutability. Fortunately, there is a fix as well. You only need to provide a custom securitymanager. So that, when there is any breach, program will throw an exception instead of breaking the immutability.

Something similar to this code will help fix this:

System.setSecurityManager(new SecurityManager() {
    @Override
    public void checkPermission(Permission perm) {
         if ("suppressAccessChecks".equals(perm.getName())) {
            throw new SecurityException("Security Violation on SupressAccessChecks");
        }
    }
});

Leave a Reply