How to prevent a collection from being exposed by getters/setters Intended Audience Prerequisites Steps Naming conventions
Intended Audience
Anyone who does not want to expose their collection fields.
Prerequisites
Enumerations or iterators can be used to list all elements of a container
without providing means of modifications (well, Iterators provide a remove
method, but its up to the implementation if this method really does
anything). Castor can use enumerations or iterators instead of a getter method
to marshal a collection.
By using add methods collections can also be unmarshalled without a
setter method.
Steps
Consider the following container object:
public class ObjectWithCollection {
protected Vector strings = new Vector();
public void addString(String string) {
strings.add(string);
}
public Iterator iterateStrings() {
return strings.iterator();
}
} |
|
To provide better data encapsulation, only the addString() and
iterateStrings() methods are made available publically, and as a
result, the collection strings is not exposed via getters or
setters.
The mapping file for above ObjectWithCollection - with the
intention to instruct Castor to use the method iterateString()
- looks as follows:
<mapping>
<class name="ObjectWithContainer">
<field name="strings" type="string" collection="vector"
get-method="iterateStrings" set-method="addString"/>
</class>
</mapping> |
|
Naming conventions
Please note that for this mechanism to work, the method returning an
java.util.Iterator for your collection member has to start with
the prefix iterate.
The same mechanism works for methods returning java.util.Enumeration
as well. In this case, the method prefix needs to be enum, and the
method specified needss to return java.util.Enumeration.
|