Because of the way that objects are persisted within the framework
Java's new operator should not be used to create new naked
objects. Instead, create a new persistent object using the utility method
createInstance provided by the
org.nakedobjects.object.AbstractNakedObject superclass.
Like most factory methods this returns an instance using a superclass
reference - in this case
org.nakedobjects.object.NakedObject - and so must be cast
into its real type before it can be used. This method takes a
java.lang.Class object, which specifies what class of
naked object to create. The example below creates a
Location object:
Location home;
home = (Location) createInstance(Location.class);
Sometimes it is necessary to create non-persistent (or 'transient')
naked objects, either for use outside the shared object space or as part
of a longer creation process, where the user will place the object into
the shared space later. A transient object can be created using the
createTransientInstance utility method. This will
return a properly initialized transient object. As with the
createInstance method, this will need its reference to
be cast to its real type. Note also that it is illegal (because it is
illogical) for any persistent object to reference a transient object.
Therefore, do not attempt to set up a field within a persistent object using this
method.
Calling makePersistent on a transient object will
make that object, and all the objects it contains, persistent. The
following example shows a non-persistent object being created, and then
being made persistent:
Location away;
away = (Location) createTransientInstance(Location.class);
:
:
away.makePersistent();
This following method is an actual object creation example taken
from the City class:
public Location actionNewLocation() {
Location loc = (Location) createInstance(Location.class);
loc.setCity(this);
return loc;
}
As these two creation methods are available you should avoid using
the new operator. If, however, you have not subclassed
org.nakedobjects.object.AbstractNakedObject then you will
have to create an object this way. It then becomes your responsibility
to call the created method, and if the object is to be
persisted, to call the makePersistent method as
well.
|