Reputation: 4747
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?
Upvotes: 2
Views: 803
Reputation: 3321
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.
Upvotes: 1
Reputation: 39606
In the general case, no, it's not possible. In a very limited case, you can wrap someType in a class that provides the same interface (see Collections.unmodifiableList() for an example).
However, there's no equivalent to "pass a const pointer and the compiler will only allow you to call const functions on it".
Upvotes: 5
Reputation: 16015
No, it's not possible. You have to either pass in a copy of the object, or just rely on knowing what actions make state changes to the object and avoid calling them - the compiler won't help you.
Upvotes: 1
Reputation: 83852
No, you can not prevent the object being modified via its setXXX() (or similar) methods. You could hand in a clone or a copy of it, though.
Upvotes: 2