Getting started¶
The first clone¶
Cloners.clone() copies the whole graph reachable from the object: every object is copied once, so shared references
stay shared and cycles stay cycles in the clone. Immutable JDK objects (strings, boxed numbers, java.time values and
others) are not copied, the clone references the same instances, see JDK types.
No constructors of your classes are called (except copy constructors added by the build tools): objects are created the way deserialization creates them, and their fields are copied.
Cloners¶
A Cloner is configured once and reused:
Cloner cloner = Cloners.builder()
.typeAction(Predicates.subclass(DataSource.class), CopyAction.ORIGINAL)
.build();
Order clone = cloner.clone(order);
| Method | Cloner |
|---|---|
Cloners.defaults() |
the default cloner, the same as Cloners.builder().build() |
Cloners.builder() |
a builder of a configured cloner, see Configuration |
Cloners.clone(object) |
clones with a new default cloner |
Cloners are thread safe: every call of clone() has its own state. Building a cloner probes the JVM and prepares
caches, so keep a configured cloner, for example in a static field or a bean, instead of building one per call.
Errors¶
Everything that goes wrong while cloning is a ClonerException, an unchecked exception; checked exceptions of
custom copiers are wrapped into it.
UncopyableObjectException, a subclass of it, means that the graph contains an object which cannot be copied
meaningfully: a thread, a reference, an open file, a socket, a process, an executor. Decide what the clone gets:
Cloner cloner = Cloners.builder()
// the clone works with the same executor
.typeAction(ExecutorService.class, CopyAction.ORIGINAL)
// the clone has no worker thread
.fieldAction(Task.class, "worker", CopyAction.CLEAR)
.build();
See Troubleshooting for other messages.
Java modules¶
The jar is a multi-release jar with the module io.github.sugarcubes.cloner:
On the module path the JVM resolves only the modules which the application requires, and the optional modules of
the cloner are not among them: require jdk.unsupported, which gives the cloner Unsafe, otherwise it creates objects
only by their constructors without arguments and reaches only the fields of open packages, see
Dependencies. With it the default toolset reaches the fields of any class, see
Toolsets. Classes of your named modules are cloned faster with generated copiers if their packages are
open to the cloner:
Classes on the classpath need nothing.