Java serialization is a mechanism to transform an object into a byte stream, and back again via Deserialization. This is important for anything which needs to be transmitted to another device/service such as writing to a file, across a network, etc.
In order to do this, we need to implement the Serializable
Interface. This provides a consistent method for calling and returning items to be serialized or deserialized so that other methods/objects can accept your object as a parameter. We can pass them even if they are not an object we know about because of the polymorphic nature of the Java objects, and how they can take on a type of an interface they implement.
How does Java serialization work?
Java serialization uses collects all the data from the object’s fields that need to be serialized. This includes private and final fields. (Notice it doesn’t include methods, that is because we’re only sending data.)
If an attribute is an object, that object is serialized as well. This will need to occur recursively until we are down to a single stream.
Even though you might have getters and setters in your class, these functions are not used when serializing an object in Java.
How does Java deserialization work?
When deserializing a byte stream back to an object it does not use the constructor.
Instead it creates an empty object and uses reflection to write the data to the fields. Just like with serialization, private and final fields are also included in this process.
So what is Reflection
Reflection is an API which is used to examine or modify the behavior of methods, classes, interfaces, and properties at runtime.
Luckily the Serialization does this all for us, because it is making it so we don’t risk missing data behind the scenes that is either private, or doesn’t have public accessors.
Reflection API can access private methods and variables of a class which could be a security threat. Which is potentially dangerous for not only security reasons, but also potential leaks about intellectual property.
Reflection API is a powerful capability provided by Java. But it has some limitations, such as slower performance, security vulnerability, and permission issues.
What is Data Serialization in Java was originally found on Access 2 Learn
2 Comments
Comments are closed.