1

Can anybody tell how we can prevent a user to modify the values of an mutable object define in an immutable class ?

Example : We have a immutable Student class, which contains final reference of Address class, which is mutable. I want to prevent the user to make any change in Address class?

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
Ashish Panery
  • 1,196
  • 3
  • 13
  • 24

1 Answers1

1

Arrange for Address to be an interface. Make your mutable MutableAddress as normal and make an ImmutableAddress that wraps it preventing write access to the fields.

interface Address {

    public String getNumber();

    public void setNumber(String number) throws IllegalAccessException;

    public String getStreet();

    public void setStreet(String street) throws IllegalAccessException;

    public String getZip();

    public void setZip(String zip) throws IllegalAccessException;

}

class MutableAddress implements Address {

    String number;
    String street;
    String zip;

    @Override
    public String getNumber() {
        return number;
    }

    @Override
    public void setNumber(String number) {
        this.number = number;
    }

    @Override
    public String getStreet() {
        return street;
    }

    @Override
    public void setStreet(String street) {
        this.street = street;
    }

    @Override
    public String getZip() {
        return zip;
    }

    @Override
    public void setZip(String zip) {
        this.zip = zip;
    }

}

class ImmutableAddress implements Address {

    private final Address address;

    public ImmutableAddress(Address address) {
        this.address = address;
    }

    @Override
    public String getNumber() {
        return address.getNumber();
    }

    @Override
    public void setNumber(String number) throws IllegalAccessException {
        throw new IllegalAccessException("Cannot write to this field.");
    }

    @Override
    public String getStreet() {
        return address.getStreet();
    }

    @Override
    public void setStreet(String street) throws IllegalAccessException {
        throw new IllegalAccessException("Cannot write to this field.");
    }

    @Override
    public String getZip() {
        return address.getZip();
    }

    @Override
    public void setZip(String zip) throws IllegalAccessException {
        throw new IllegalAccessException("Cannot write to this field.");
    }

}

Alternatively, wrap it in a Proxy. This is much more complicated but can help when you do not have access to the sources.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213