SteelReed

Search

Search posts, questions…

OOP & DesignQuestion 18 / 42

Middle

Why avoid clone(), finalize() and Java serialization, and what should you use instead?

Short answer

All three create or destroy objects around the constructor and break easily. Replace them with copy constructors, try-with-resources and JSON/Protobuf.

Mechanism Main problem
clone() shallow copy by default, Cloneable is an odd marker, clashes with final fields
finalize() unknown when it runs, may never run, slows down GC
Java serialization large attack surface, format tied to class structure

3 points to say:

  1. clone() copies shallowly: use a copy constructor.
  2. finalize() is going away: use try-with-resources.
  3. Java serialization is dangerous: use JSON.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.