Recently in an interview I was asked a question:
There are 100 properties in a Java class and I should be able to serialize only 2 of the properties. How is this possible?
Marking all the 98 properties was not the answer as it is not efficient. My answer was to carve out those properties into a separate class and make it serializable.
But I was told that, I will not be allowed to modify the structure of the class. Well, I tried to find an answer in online forums, but in vain.
The answer is transient keyword of java. if you make a property of a class transient it will not be serialized or deserialized. For example:
private transient String nonSerializeName;
You could override the serialization behavior without using Externalizable interface,
you need to add following methods and do the needful there,
private void writeObject(ObjectOutputStream out) throws IOException;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;
for example class could look like this,
class Foo{
private int property1;
private int property2;
....
private int property100;
private void writeObject(ObjectOutputStream out) throws IOException
{
out.writeInt(property67);
out.writeInt(property76);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
property67 = in.readInt();
property76 = in.readInt();
}
}
Refer this for more details
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With