DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Improving Serialization and Memory Efficiency With a LongConverter
  • Software Design Patterns and Principles
  • Comprehensive Proxy Server Guide: Types, Applications, and Developer Examples
  • CORS Anywhere on Pure NGINX Config

Trending

  • Unlocking AI Coding Assistants Part 1: Real-World Use Cases
  • Fraud Detection Using Artificial Intelligence and Machine Learning
  • Java 23 Features: A Deep Dive Into the Newest Enhancements
  • How to Format Articles for DZone

Serialization Proxy Pattern Example

By 
Michal Jastak user avatar
Michal Jastak
·
Jun. 17, 14 · Interview
Likes (0)
Comment
Save
Tweet
Share
17.5K Views

Join the DZone community and get the full member experience.

Join For Free
There are books, which change your life immensely. One of such books is "Effective Java" by Joshua Bloch. Below you may find small experiment, which was inspired by Chapter 11 of this book - "Serialization".

Suppose that we have a class designed for inheritance, which is not Serializable itself, and has no parameterless constructor, like in this example:
public class CumbersomePoint {

    private String name;

    private double x;

    private double y;

    protected CumbersomePoint(double x, double y, String name) {
        this.x = x;
        this.y = y;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    ...
}
Now when we extend this class, for example in following way:
public class ConvenientPoint extends CumbersomePoint implements Serializable {

    public ConvenientPoint(double x, double y, String name) {
        super(x, y, name);
    }

    ...
}
and try to serialize and then deserialize any of ConvenientPoint instances, we'll quickly encounter beautifulInvalidClassException, complaining that there is no valid constructor. Situation looks kinda hopeless, until you apply technique known as Serialization Proxy Pattern.

We will start by adding to the ConvenientPoint class following inner class:
private static class SerializationProxy implements Serializable {

        private String name;

        private double x;

        private double y;

        public SerializationProxy(ConvenientPoint point) {
            this.name = point.getName();
            this.x = point.getX();
            this.y = point.getY();
        }

        private Object readResolve() {
            return new ConvenientPoint(x, y, name);
        }

    }
The SerializationProxy class will represent the logical state of enclosing class instance. We will have to add also following method to ConvenientPoint class:
   private Object writeReplace() {
        return new SerializationProxy(this);
    }

Now when the ConvenientPoint instance will be serialized, it will nominate its replacement, thanks to writeReplacemethod - SerializationProxy instance will be serialized instead of ConvenientPoint.

From the other side, when SerializationProxy will be deserialized, readResolve method usage will nominate its replacement, being ConvenientPoint instance.

As you see, we've made ConvenientPoint serializable, regardless of missing parameterless constructor of non-serializable parent class.

One more remark, at the end of this post - if you want to protect against breaking class invariants, enforced by the constructor, you may add following method to class using Serialization Proxy Pattern (ConvenientPoint in our example): 
   private void readObject(ObjectInputStream stream) throws InvalidObjectException {
        throw new InvalidObjectException("Use Serialization Proxy instead.");
    }
It will prevent deserialization of the enclosing class.
Proxy pattern Serialization

Published at DZone with permission of Michal Jastak, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Improving Serialization and Memory Efficiency With a LongConverter
  • Software Design Patterns and Principles
  • Comprehensive Proxy Server Guide: Types, Applications, and Developer Examples
  • CORS Anywhere on Pure NGINX Config

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!