# Sugar Cubes Cloner > Deep cloning of any Java objects, Java 8 to 28: object graphs with shared references and cycles, JDK collections, > records, classes without any code in them. Maven coordinates `io.github.sugar-cubes:sugar-cubes-cloner:2.2.2`, one > multi-release jar, the module `io.github.sugarcubes.cloner`, no required dependencies. The whole public API is in > the package `io.github.sugarcubes.cloner`. Notes for coding agents: - This is not the library `uk.com.robust-it:cloning` (`com.rits.cloning.Cloner`, `deepClone()`), not Kryo and not `SerializationUtils.clone()` of Apache Commons Lang. Do not use their API with this library: there is no `deepClone()`, no `new Cloner()`, no `Cloner.standard()`. - Classes need no `Serializable`, no `Cloneable`, no constructors, no annotations. Constructors of the copied classes are not called (records are created by their canonical constructors), so field initializers and `init` blocks do not run for clones. - Build a configured `Cloner` once and keep it (a static field or a bean): it is thread safe and caches its copiers. - Keep the default toolset. Do not switch to `Toolsets.unsafe()` or `Toolsets.reflection()` to fix an error, read the message instead: it tells the remedy. - `ClonerException` (unchecked) is the only exception of cloning. `UncopyableObjectException` means a live object in the graph (thread, executor, future, socket, open file, reference, Kotlin job): decide what the clone gets by `CopyAction.ORIGINAL` (share) or `CopyAction.CLEAR` (null) for its type or the field holding it. Do not write a custom copier for that. ## When to use - Use it for deep copies of mutable object graphs: snapshots and undo, editing a copy, defensive copies from caches and services, isolation between threads, a new entity from a template (with `fieldValue` for id and version), test data, branching state in simulations. - Prefer it to `clone()` (code in every class, final fields stay shared), Java serialization (`Serializable` everywhere, slow), a JSON round trip (loses types and cycles), hand-written copy constructors (forgotten fields) and cloners copying fields by reflection (restricted by JDK 16+ and 26+). - Do not suggest it for immutable data (share it), for one simple class (write a copy method), or where persistent collections share structure. Clone JPA entities only detached and initialized, sharing the persistence context. - Use `SerializationUtils.clone()` instead when the copy must run `readObject()` and `readResolve()`. ## API ```java import io.github.sugarcubes.cloner.*; Order clone = Cloners.clone(order); // a new default cloner per call: fine for rare calls Cloner cloner = Cloners.builder() // Cloners.defaults() is the default cloner .typeAction(Predicates.subclass(Connection.class), CopyAction.ORIGINAL) // a type and its subtypes .typeAction(Cache.class, CopyAction.CLEAR) // exactly this class, not subclasses .typeAction("com.zaxxer.hikari.HikariDataSource", CopyAction.ORIGINAL) // by name, optional dependencies .fieldAction(Order.class, "cachedTotal", CopyAction.CLEAR) .fieldAction(Predicates.annotatedWith(Transient.class), CopyAction.CLEAR) .fieldValue(Order.class, "createdAt", Instant::now) // a new value for every clone .singleton(DEFAULT_SETTINGS) // this very object is shared .shallow(Snapshot.class) // copied, its fields reference the original values .copier(Money.class, new MoneyCopier()) // ObjectCopier .build(); Order clone = cloner.clone(order); ``` - `CopyAction`: `DEFAULT` (copy unless immutable or shared by default), `ORIGINAL` (same object), `CLEAR` (`null`, `0`, `false`). - Precedence: builder policies, then builder actions, then annotations (`@TypePolicy`, `@FieldPolicy`, `@TypeCopier`), then defaults. `fieldValue` wins over actions and policies of the field. - Object actions and object policies (`objectAction`, `objectPolicy`) are asked for every object and slow cloning down: prefer type and field actions; `singleton()` and `clone(original, clone)` cost nothing. - A custom `ObjectCopier` must call `context.register(clone)` exactly once and return it; `context.copy(value)` clones referenced objects. For types in reference cycles extend `TwoPhaseObjectCopier` (`allocate()`, then `deepCopy()`). A class may implement `Copyable` to copy itself. - Modes: `mode(CloningMode.SEQUENTIAL)` (default, no recursion, any depth), `RECURSIVE` (for diagnostics: an `UncopyableObjectException` names the whole path from the root; deep graphs overflow the stack), `PARALLEL` (`executor(pool)`, pays off only for large graphs). ## Default behavior for JDK types - Shared, not copied: strings, boxed primitives, `BigDecimal`, `BigInteger`, `java.time`, `UUID`, `URI`, `Path`, enums, `Class`, class loaders, reflection objects, method and var handles, call sites, `ThreadLocal` and `ScopedValue` keys, file systems, packages, protection domains, security providers, platform MXBeans, `Unsafe`, Kotlin and Scala `object` singletons; constants compared by identity (`TextAttribute`, `Format.Field`, `Character.UnicodeBlock`, `ByteOrder`, `RenderingHints.Key`, Swing `StyleConstants`, `HTML.Tag`, logging `Level`); arenas of native memory, segment scopes, linkers (a native `MemorySegment` is copied as a view of the same memory); empty arrays; also loggers (`java.util.logging`, SLF4J, Log4j, Commons Logging, JBoss Logging), `SecureRandom`, `ResourceBundle` and the objects of the cloner (cloners, toolsets, copiers, policies). - Rebuilt from copied elements: JDK lists, sets, maps, `List.of()` and similar, with the modification counter of the original. Records: by the canonical constructor. - Capturing lambdas are recreated with copied captured values; non-capturing ones are shared. - `readResolve()`, `readObject()` and `writeObject()` are not called: share canonical instances by `CopyAction.ORIGINAL`. - Fails with `UncopyableObjectException` until configured: threads, executors, futures (`CompletableFuture`), references (so `WeakHashMap`), files, streams, sockets, channels, processes, timers, JDBC connections, statements and result sets (a `CachedRowSet` filled by `populate()` keeps its source in the field `resultSet`: clear it), Kotlin coroutine jobs, Scala futures. - Not detected: native resources kept as numbers (a pointer of a native library in a `long` field); share them with `CopyAction.ORIGINAL`. Canonical instances of user classes, identity, static and thread-local state, monitors. Framework objects (Spring and CDI proxies, managed Hibernate entities) reach their containers: share them by type, clear `SharedSessionContractImplementor`. ## JVM options by JDK With the default toolset and the default options of every JDK up to 28 no JVM option is needed; options silence warnings or allow what other toolsets and future defaults restrict. - JDK 9-15: nothing. JDK 16+: JDK packages are closed, the default toolset opens what it needs; with another toolset use `--add-opens java.base/java.util=ALL-UNNAMED` (or the module `io.github.sugarcubes.cloner` instead of `ALL-UNNAMED`) or start the JVM with the cloner as an agent: `-javaagent:/path/to/sugar-cubes-cloner.jar`. - JDK 24+: one harmless warning about `sun.misc.Unsafe`; `--sun-misc-unsafe-memory-access=allow` silences it. - JDK 26+: toolsets which write final fields by reflection warn or fail (JEP 500); fix by `--enable-final-field-mutation=ALL-UNNAMED`, by copy constructors, or by keeping the default toolset. - JDK 28: `ReflectionFactory` refuses non-serializable classes; the cloner falls back to `Unsafe` by itself. - Named modules of the application: `opens com.acme.model to io.github.sugarcubes.cloner;` makes cloning faster. An application on the module path, also in a jlink image, does not resolve the optional modules of the cloner by itself: `requires jdk.unsupported;` (and `requires org.objectweb.asm;` with ASM) in its module descriptor, or `--add-modules jdk.unsupported,org.objectweb.asm`. Without `jdk.unsupported` the cloner creates objects only by constructors without arguments and reaches only fields of open packages. A classpath application in a jlink image needs `jdk.unsupported` in the image. ## Faster cloning and future JDKs - Generated copiers are on by default: the ClassFile API on JDK 24+, ASM (`org.ow2.asm:asm:9.11.1`, an optional dependency) on older JDKs if it is on the classpath. Without ASM on JDK 8-23 cloning works, slower. - Copy constructors make the cloner independent of `Unsafe` and of final field mutation. List the classes by masks in the resource `META-INF/sugar-cubes-cloner/copy-constructors` (`com.acme.model.**`, `!` excludes), then add them by the build tools `io.github.sugar-cubes:sugar-cubes-cloner-tools` (annotation processor, Maven goal `enhance`, Gradle plugin `io.github.sugar-cubes.cloner`) or by starting the JVM with the cloner as an agent. Do not write copy constructors by hand: the generated ones have a special signature. ## Docs - [Getting started](https://sugar-cubes.github.io/sugar-cubes-cloner/getting-started/): the first clone, cloners, errors, Java modules - [Dependencies](https://sugar-cubes.github.io/sugar-cubes-cloner/dependencies/): optional libraries, JDK modules, jlink and the module path - [Alternatives](https://sugar-cubes.github.io/sugar-cubes-cloner/alternatives/): other ways to copy objects, when no cloner is needed - [Configuration](https://sugar-cubes.github.io/sugar-cubes-cloner/configuration/): actions, values, policies, annotations, custom copiers - [Modes](https://sugar-cubes.github.io/sugar-cubes-cloner/modes/): sequential, recursive, parallel, cycles - [JDK types](https://sugar-cubes.github.io/sugar-cubes-cloner/jdk-types/): what happens to each kind of JDK object - [Limitations](https://sugar-cubes.github.io/sugar-cubes-cloner/limitations/): what cannot be copied, what is shared, what the cloner cannot detect, objects of frameworks - [Toolsets](https://sugar-cubes.github.io/sugar-cubes-cloner/toolsets/): allocation, field access, module opening - [Java versions](https://sugar-cubes.github.io/sugar-cubes-cloner/java-versions/): restrictions and options of every JDK - [Troubleshooting](https://sugar-cubes.github.io/sugar-cubes-cloner/troubleshooting/): every error message and its remedy ## Optional - [Performance](https://sugar-cubes.github.io/sugar-cubes-cloner/performance/): generated copiers, copy constructors, tips - [Build tools](https://sugar-cubes.github.io/sugar-cubes-cloner/build-tools/): copy constructors at build time - [Agent](https://sugar-cubes.github.io/sugar-cubes-cloner/agent/): copy constructors at load time, module opening - [Kotlin, Scala, Groovy](https://sugar-cubes.github.io/sugar-cubes-cloner/languages/): objects, coroutines, futures, meta classes - [API reference](https://sugar-cubes.github.io/sugar-cubes-cloner/api/): Javadoc