Don Li Don Li - 2 years ago 71
Java Question

Is it possible to make an object "Read Only" to a method

If an object reference is passed to a method, is it possible to make the object "Read Only" to the method?

Answer Source

Not strictly speaking. That is, a reference that can mutate an object can not be turned into a reference that can not mutate an object. Also, there is not way to express that a type is immutable or mutable, other than using conventions.

The only feature that ensure some form of immutability would be final fields - once written they can not be modified.

That said, there are ways to design classes so that unwanted mutation are prevented. Here are some techniques:

  • Defensive Copying. Pass a copy of the object, so that if it is mutated it doesn't break your internal invariants.

  • Use access modifiers and/or interface to expose only read-only methods. You can use access modifieres (public/private/protected), possibly combined with interface, so that only certain methods are visible to the other object. If the methods that are exposed are read-only by nature, you are safe.

  • Make your object immutable by default. Any operation on the object returns actually a copy of the object.

Also, note that the API in the SDK have sometimes methods that return an immutable version of an object, e.g. Collections.unmodifiableList. An attempt to mutate an immutable list will throw an exception. This does not enforce immutability statically (at compile-time with the static type system), but is is a cheap and effective way to enforce it dynamically (at run-time).

There has been many research proposals of Java extension to better control of aliasing, and accessibility. For instance, addition of a readonly keyword. None of them is as far as I know planned for inclusion in future version of Java. You can have a look at these pointers if you're interested:

The checker framework is very interesting. In the Checker Framework, look at Generic Universe Types checker, IGJ immutability checker, and Javari immutability checker. The framework works using annotations, so it is not intrusive.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download