When I pass an immutable type object(String, Integer,.. ) as final to a method I can achieve the characters of a C++ constant pointer. But how can I enforce such behavior in objects which are mutable?
public void someMethod(someType someObject){ /* * code that modifies the someObject's state * */ }
All I want is to prevent someMethod from modifying the state of someObject without making any change in someType. Is this possible?
No, I don’t think this is possible. The normal approach is to create an adapter for SomeType where all the methods changing state throws UnsupportedOperationException. This is used by for instance java.util.Collections.unmodifiable*-functions.
There are several approaches to this:
This will of course only give you run-time checking, not compiletime. If you want compile-time, you can let SomeType be an interface (or a superclass) with no write-methods, only read.